Maximum triplet sum in array in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array. Our task is to create a program that will find the maximum triplet sum in the array i.e. find the set of three elements whose sum is maximum.

Let’s take an example to understand the problem,

Input − array = {4, 6, 1, 2}

Output − 12

Explanation

all triplets are :
(4, 6, 1) = 4+6+1 = 11
(4, 6, 2) = 4+6+1 = 12
(4, 1, 2) = 4+6+1 = 7
(6, 1, 2) = 4+6+1 = 9
The maximum triplet sum is 12

One simple approach to solve the problem is what we have depicted in the example, which is taking sum values for all triplet pairs and then finding the maximum of them. But this approach is not effective as with the length of all the number of triplets will become large.

In this method, we will run three loops that will find all possible sum triplets and if this triplet’s sum is larger than maxsum then we will initialize this triplet sum as maxsum.

Example

Program to illustrate our solution,

 Live Demo

#include <iostream>
using namespace std;
int maxSum(int arr[], int n){
   int maxSum = 0;
   int i, j, k;
   for (i = 0; i < n; i++)
      for (j = i + 1; j < n; j++)
         for (k = j + 1; k < n; k++)
            if (maxSum < arr[i] + arr[j] + arr[k]) maxSum = arr[i] + arr[j] + arr[k];
   return maxSum;
}
int main(){
   int arr[] = { 3, 5, 7 ,1, 9, 0 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The maximum triplet sum of the array is "<<maxSum(arr, n);
   return 0;
}

Output

The maximum triplet sum of the array is 21

An effective approach will be sorting the array and then finding sum of the last three elements of the array which will be the maximum sum of triplets.

Example

Program to illustrate the solution,

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int maxSum(int arr[], int n) {
   sort(arr, arr + n);
   return arr[n - 1] + arr[n - 2] + arr[n - 3];
}
int main() {
   int arr[] = { 3, 5, 9, 1, 2, 8, 7 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The maximum triplet sum of the array is "<<maxSum(arr, n);
   return 0;
}

Output

The maximum triplet sum of the array is 24
raja
Published on 10-Feb-2020 14:00:30
Advertisements