Problem
A triplet is an array of three integers. You are given a 2D integer array triplets
, where triplets[i] = [ai, bi, ci]
describes the ith
triplet. You are also given an integer array target = [x, y, z]
that describes the triplet you want to obtain.
To obtain target
, you may apply the following operation on triplets
any number of times (possibly zero):
- Choose two indices (0-indexed)
i
andj
(i != j
) and updatetriplets[j]
to become[max(ai, aj), max(bi, bj), max(ci, cj)]
.- For example, if
triplets[i] = [2, 5, 3]
andtriplets[j] = [1, 7, 5]
,triplets[j]
will be updated to[max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5]
.
- For example, if
Return true
if it is possible to obtain the target
triplet [x, y, z]
as an element of triplets
, or false
otherwise.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 – Greedy Filtering and Merging
Intuition
The key idea is to only consider triplets where each value does not exceed the corresponding value in the target. By greedily merging these valid triplets, we can maximize each dimension and try to reach the target. If we can form the target triplet by combining these, the answer is true.
Approach
- Initialize a result triplet
ans
as[0, 0, 0]
. - Iterate through each triplet in the input:
- If all elements of the triplet are less than or equal to the corresponding elements in the target, consider it valid.
- For each valid triplet, update
ans
by taking the maximum of each coordinate with the current triplet.
- After processing all triplets, check if
ans
matches the target triplet. - Return true if they match, false otherwise.
Code
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(N)
, where N is the number of triplets. - 🧺 Space complexity:
O(1)
, as only a fixed-size array is used.