https://www.geeksforgeeks.org/find-maximum-sum-triplets-array-j-k-ai-aj-ak/
Time complexity: O(n*log(n))
Given an array of positive integers of size n. Find the maximum sum of triplet( ai + aj + ak ) such that 0 <= i < j < k < n and ai < aj < ak.
Input: a[] = 2 5 3 1 4 9 Output: 16 Explanation: All possible triplets are:- 2 3 4 => sum = 9 2 5 9 => sum = 16 2 3 9 => sum = 14 3 4 9 => sum = 16 1 4 9 => sum = 14 Maximum sum = 16
Best and efficient approach is use the concept of maximum suffix-array and binary search.
- For finding maximum number greater number greater than given number beyond it, we can maintain a maximum suffix-array array such that for any number(suffixi) it would contain maximum number from index i, i+1, … n-1. Suffix array can be calculated in O(n) time.
- For finding maximum number smaller than the given number preceding it, we can maintain a sorted list of numbers before a given number such we can simply perform a binary search to find a number which is just smaller than the given number. In C++ language, we can perform this by using set associative container of STL library.
Simple Approach is to traverse for every triplet with three nested ‘for loops’ and find update the sum of all triplets one by one. Time complexity of this approach is O(n3) which is not sufficient for larger value of ‘n’.
Better approach is to make further optimization in above approach. Instead of traversing through every triplets with three nested loops, we can traverse through two nested loops. While traversing through each number(assume as middle element(aj)), find maximum number(ai) smaller than aj preceding it and maximum number(ak) greater than aj beyond it. Now after that, update the maximum answer with calculated sum of ai + aj + ak