Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find maximum sum of triplets in an array such than i < j < k and a[i] < a[j] < a[k] in Python
Given an array of positive numbers, we need to find the maximum sum of a triplet (a[i] + a[j] + a[k]) such that 0 ? i
For example, if the input is A = [3,6,4,2,5,10], the valid triplets are (3,4,5): sum = 12, (3,6,10): sum = 19, (3,4,10): sum = 17, (4,5,10): sum = 19, and (2,5,10): sum = 17. The maximum sum is 19.
Algorithm Approach
The solution uses a brute force approach with the following steps ?
For each middle element at index
i, find the maximum smaller element on the leftFind the maximum larger element on the right
If both exist, calculate the triplet sum and update the result
Implementation
def get_max_triplet_sum(A):
n = len(A)
res = 0
# Consider each element as middle element
for i in range(1, n - 1):
first_max = 0 # Maximum element smaller than A[i] on left
second_max = 0 # Maximum element larger than A[i] on right
# Find maximum element smaller than A[i] on left side
for j in range(0, i):
if A[j] < A[i]:
first_max = max(first_max, A[j])
# Find maximum element larger than A[i] on right side
for j in range(i + 1, n):
if A[j] > A[i]:
second_max = max(second_max, A[j])
# If both elements exist, update result
if first_max and second_max:
res = max(res, first_max + A[i] + second_max)
return res
# Test the function
A = [3, 6, 4, 2, 5, 10]
result = get_max_triplet_sum(A)
print(f"Maximum triplet sum: {result}")
Maximum triplet sum: 19
How It Works
Let's trace through the example [3, 6, 4, 2, 5, 10] ?
i=1 (A[1]=6): Left max smaller = 3, Right max larger = 10, Sum = 3+6+10 = 19
i=2 (A[2]=4): Left max smaller = 3, Right max larger = 10, Sum = 3+4+10 = 17
i=3 (A[3]=2): No smaller element on left
i=4 (A[4]=5): Left max smaller = 4, Right max larger = 10, Sum = 4+5+10 = 19
Time Complexity
| Aspect | Complexity | Explanation |
|---|---|---|
| Time | O(n²) | Nested loops for each middle element |
| Space | O(1) | Only using constant extra variables |
Conclusion
This algorithm finds the maximum sum triplet by considering each element as the middle element and finding optimal left and right elements. The O(n²) time complexity makes it suitable for moderate-sized arrays.
