LeetCode-in-Java

3572. Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values

Medium

You are given two integer arrays x and y, each of length n. You must choose three distinct indices i, j, and k such that:

Your goal is to maximize the value of y[i] + y[j] + y[k] under these conditions. Return the maximum possible sum that can be obtained by choosing such a triplet of indices.

If no such triplet exists, return -1.

Example 1:

Input: x = [1,2,1,3,2], y = [5,3,4,6,2]

Output: 14

Explanation:

Example 2:

Input: x = [1,2,1,2], y = [4,5,6,7]

Output: -1

Explanation:

Constraints:

Solution

public class Solution {
    public int maxSumDistinctTriplet(int[] x, int[] y) {
        int index = -1;
        int max = -1;
        int sum = 0;
        for (int i = 0; i < y.length; i++) {
            if (y[i] > max) {
                max = y[i];
                index = i;
            }
        }
        sum += max;
        if (max == -1) {
            return -1;
        }
        int index2 = -1;
        max = -1;
        for (int i = 0; i < y.length; i++) {
            if (y[i] > max && x[i] != x[index]) {
                max = y[i];
                index2 = i;
            }
        }
        sum += max;
        if (max == -1) {
            return -1;
        }
        max = -1;
        for (int i = 0; i < y.length; i++) {
            if (y[i] > max && x[i] != x[index] && x[i] != x[index2]) {
                max = y[i];
            }
        }
        if (max == -1) {
            return -1;
        }
        sum += max;
        return sum;
    }
}