Find Maximum Sum Triplet Array

Here's a clean, professional breakdown of the Maximum Sum Increasing Triplet (i < j < k and a[i] < a[j] < a[k]) problem and its various approaches:


Problem Statement

Given an array of positive integers of size n, find the maximum sum of a triplet (a[i], a[j], a[k]) such that:

Return the maximum possible sum of such a triplet. If no such triplet exists, return 0.


Example

Input: a[] = [2, 5, 3, 1, 4, 9]
Output: 16

Explanation:
Valid triplets with increasing values:


Naive Approach (O(n³))

Idea:

Use three nested loops and check for every triplet.

Time Complexity:


Better Approach (O(n²))

Idea:

Fix the middle element a[j] and:

Code:

static int maxTripletSum(int arr[], int n) {
    int ans = 0;
    for (int i = 1; i < n - 1; ++i) {
        int max1 = 0, max2 = 0;

        for (int j = 0; j < i; ++j)
            if (arr[j] < arr[i])
                max1 = Math.max(max1, arr[j]);

        for (int j = i + 1; j < n; ++j)
            if (arr[j] > arr[i])
                max2 = Math.max(max2, arr[j]);

        if (max1 > 0 && max2 > 0)
            ans = Math.max(ans, max1 + arr[i] + max2);
    }
    return ans;
}

Time Complexity:

Space:


Optimized Approach (O(n log n)) using TreeSet + Suffix Array

Idea:

Code:

import java.util.*;

class Solution {
    public static int maxTripletSum(int arr[], int n) {
        int[] maxSuff = new int[n + 1];
        maxSuff[n] = 0;

        // Build suffix array
        for (int i = n - 1; i >= 0; --i)
            maxSuff[i] = Math.max(maxSuff[i + 1], arr[i]);

        TreeSet<Integer> left = new TreeSet<>();
        left.add(Integer.MIN_VALUE);

        int ans = 0;

        for (int i = 0; i < n - 1; i++) {
            if (maxSuff[i + 1] > arr[i]) {
                int smaller = left.lower(arr[i]);
                if (smaller != null && smaller != Integer.MIN_VALUE) {
                    int sum = smaller + arr[i] + maxSuff[i + 1];
                    ans = Math.max(ans, sum);
                }
            }
            left.add(arr[i]);
        }
        return ans;
    }

    public static void main(String[] args) {
        int arr[] = { 2, 5, 3, 1, 4, 9 };
        int n = arr.length;
        System.out.println(maxTripletSum(arr, n));
    }
}

Time Complexity:

Space Complexity:


Summary

Approach Time Complexity Space Complexity Remarks
Brute Force O(n³) O(1) Too slow
Better (2 Loops) O(n²) O(1) Acceptable for small inputs
Optimized (BST+Suff) O(n log n) O(n) Best for large constraints