Merge Triplets to Form Target Triplet

medium greedy array

Problem

You are given a list of triplets, each holding three integers [a, b, c], plus a target triplet [x, y, z]. In one operation you may pick any two triplets and overwrite one of them with their element-wise maximum: [max(a₁,a₂), max(b₁,b₂), max(c₁,c₂)]. You may repeat the operation as often as you like.

Return true if some sequence of operations can make the target triplet appear in the list, and false otherwise.

Inputtriplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5]
Outputtrue
Merging [2,5,3] with [1,7,5] gives [max(2,1), max(5,7), max(3,5)] = [2,7,5], which is exactly the target.

def merge_triplets(triplets, target):
    best = [0, 0, 0]
    for a, b, c in triplets:
        if a <= target[0] and b <= target[1] and c <= target[2]:
            best[0] = max(best[0], a)
            best[1] = max(best[1], b)
            best[2] = max(best[2], c)
    return best == target
function mergeTriplets(triplets, target) {
  const best = [0, 0, 0];
  for (const [a, b, c] of triplets) {
    if (a <= target[0] && b <= target[1] && c <= target[2]) {
      best[0] = Math.max(best[0], a);
      best[1] = Math.max(best[1], b);
      best[2] = Math.max(best[2], c);
    }
  }
  return best[0] === target[0] && best[1] === target[1] && best[2] === target[2];
}
boolean mergeTriplets(int[][] triplets, int[] target) {
    int[] best = {0, 0, 0};
    for (int[] t : triplets) {
        if (t[0] <= target[0] && t[1] <= target[1] && t[2] <= target[2]) {
            best[0] = Math.max(best[0], t[0]);
            best[1] = Math.max(best[1], t[1]);
            best[2] = Math.max(best[2], t[2]);
        }
    }
    return Arrays.equals(best, target);
}
bool mergeTriplets(vector<vector<int>>& triplets, vector<int>& target) {
    vector<int> best = {0, 0, 0};
    for (auto& t : triplets) {
        if (t[0] <= target[0] && t[1] <= target[1] && t[2] <= target[2]) {
            best[0] = max(best[0], t[0]);
            best[1] = max(best[1], t[1]);
            best[2] = max(best[2], t[2]);
        }
    }
    return best == target;
}
Time: O(n) Space: O(1)