703023. Maximum triplet sum in array

Basic

Maximum Triplet Sum in Array

Summary

Given an array of integers, find the maximum sum that can be obtained by selecting three distinct elements from it. This problem is related to arrays and data structures.

Detailed Explanation

To solve this problem, we need to iterate through the array, maintaining a maximum sum found so far. For each element, we check all possible triplets (including itself) and update our maximum sum if necessary. Since the triplet sum can be computed in O(1), the time complexity of this solution is O(n^2), where n is the size of the input array.

Here's a step-by-step breakdown:

  1. Initialize max_sum to negative infinity.
  2. Iterate through the array:
    • For each element, generate all possible triplets (including itself) and compute their sum.
    • Update max_sum if the computed triplet sum is greater than the current maximum.
  3. Return max_sum.

Here's a sample diagram illustrating this process:

 1 | 2 | 3
 ---------
-  | - | -
 4 | 5 | 6
 ---------
-  | - | -

 1, 2, and 3: sum = 6 (update max_sum)
 1, 4, and 5: sum = 10 (update max_sum)
 4, 5, and 6: sum = 15 (update max_sum)

max_sum = 15

Time complexity: O(n^2) where n is the size of the input array. Space complexity: O(1), as we only need a few variables to store our maximum sum.

Optimized Solutions

Java

View on GeeksforGeeks
public class Main {
    public static int maximumTripletSum(int[] arr) {
        int max_sum = Integer.MIN_VALUE;
        for (int i = 0; i < arr.length; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                for (int k = j + 1; k < arr.length; k++) {
                    int triplet_sum = arr[i] + arr[j] + arr[k];
                    if (triplet_sum > max_sum) {
                        max_sum = triplet_sum;
                    }
                }
            }
        }
        return max_sum;
    }

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

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.