Merge Triplets to Form Target Triplet
The key idea
The merge operation only ever takes the element-wise maximum, so it can never decrease a value. A triplet that has any component strictly greater than the matching component of target is poison: merging it would push that position above target forever. Discard those triplets, then check whether the element-wise max of the survivors hits every target component exactly.
Problem
You are given a 2D array of integers triplets, where triplets[i] = [ai, bi, ci] describes the i-th triplet. You are also given an 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 i and j (i != j) and update triplets[j] to become [max(ai, aj), max(bi, bj), max(ci, cj)].
Return true if it is possible to obtain the target triplet [x, y, z] as an element of triplets, or false otherwise.
Constraints
1 <= triplets.length <= 10^5triplets[i].length == target.length == 31 <= ai, bi, ci, x, y, z <= 1000
Examples
Input: triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5]
Output: true
Input: triplets = [[3,4,5],[4,5,6]], target = [3,2,5]
Output: false
Input: triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5]
Output: true
Complexity
Time: O(n) Space: O(1)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Greedy problems
- Assign CookiesEASY
- Best Time to Buy and Sell Stock IIMEDIUM
- Boats to Save PeopleMEDIUM
- Can Place FlowersEASY
- CandyHARD
- Dota2 SenateMEDIUM
- Gas StationMEDIUM
- Hand of StraightsMEDIUM
- Increasing Triplet SubsequenceMEDIUM
- Jump GameMEDIUM
- Jump Game IIMEDIUM
- Lemonade ChangeEASY