Maximum triplet sum in array in C++

C++Server Side ProgrammingProgramming

Problem statement

Given an array, the task is to find maximum triplet sum in the array

If input array is {10, 18, -6, 12, 7, 6} then maximum triplet sum is (10 + 18 + 12) = 40

Algorithm

1. Sort the entire array
2. Take sum of last three elements

Example

#include <bits/stdc++.h>
using namespace std;
int getMaxTripletSum(int *arr, int n){
   sort(arr, arr + n);
   return arr[n - 1] + arr[n - 2] + arr[n - 3];
}
int main(){
   int arr[] = {10, 18, -6, 12, 7, 6};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Maximum triplet sum = " <<getMaxTripletSum(arr, n) << endl;
   return 0;
}

Output

When you compile and execute the above program. It generates the following output −

Maximum triplet sum = 40
raja
Published on 10-Feb-2020 09:30:30
Advertisements