Given an array arr[] of integers, the task is to find the maximum sum of any sub-sequence in the array such that any two adjacent elements in the selected sequence have at least a difference of 3 in their indices in the given array.
In other words, if you select arr[i] then the next element you can select is arr[i + 3], arr[i + 4], and so on… but you cannot select arr[i + 1] and arr[i + 2].
Examples:
Input: arr[] = {1, 2, -2, 4, 3}
Output: 5
{1, 4} and {2, 3} are the only sub-sequences
with maximum sum.Input: arr[] = {1, 2, 72, 4, 3, 9}
Output: 81
Naive approach: We generate all possible subsets of the array and check if the current subset satisfies the condition.If yes, then we compare its sum with the largest sum we have obtained till now. It is not an efficient approach as it takes exponential time .
Efficient approach: This problem can be solved using dynamic programming. Let’s decide the states of the dp. Let dp[i] be the largest possible sum for the sub-sequence starting from index 0 and ending at index i. Now, we have to find a recurrence relation between this state and a lower-order state.
In this case for an index i, we will have two choices:
- Choose the current index: In this case, the relation will be dp[i] = arr[i] + dp[i – 3].
- Skip the current index: Relation will be dp[i] = dp[i – 1].
We will choose the path that maximizes our result. Thus the final relation will be:
dp[i] = max(dp[i – 3] + arr[i], dp[i – 1])
Below is the implementation of the above approach:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to return the maximum sum // of the sub-sequence such that two // consecutive elements have a difference of // at least 3 in their indices // in the given array int max_sum( int a[], int n) { int dp[n]; // If there is a single element in the array if (n == 1) { // Either select it or don't dp[0] = max(0, a[0]); } // If there are two elements else if (n == 2) { // Either select the first // element or don't dp[0] = max(0, a[0]); // Either select the first or the second element // or don't select any element dp[1] = max(a[1], dp[0]); } else if (n >= 3) { // Either select the first // element or don't dp[0] = max(0, a[0]); // Either select the first or the second element // or don't select any element dp[1] = max(a[1], max(0, a[0])); // Either select first, second, third or nothing dp[2] = max(a[2], max(a[1], max(0, a[0]))); int i = 3; // For the rest of the elements while (i < n) { // Either select the best sum till // previous_index or select the current // element + best_sum till index-3 dp[i] = max(dp[i - 1], a[i] + dp[i - 3]); i++; } } return dp[n - 1]; } // Driver code int main() { int arr[] = { 1, 2, -2, 4, 3 }; int n = sizeof (arr) / sizeof (arr[0]); cout << max_sum(arr, n); return 0; } |
Java
// Java implementation of the approach class GFG { // Function to return the maximum sum // of the sub-sequence such that two // consecutive elements have a difference of // at least 3 in their indices // in the given array static int max_sum( int a[], int n) { int []dp = new int [n]; // If there is a single element in the array if (n == 1 ) { // Either select it or don't dp[ 0 ] = Math.max( 0 , a[ 0 ]); } // If there are two elements else if (n == 2 ) { // Either select the first // element or don't dp[ 0 ] = Math.max( 0 , a[ 0 ]); // Either select the first or the second element // or don't select any element dp[ 1 ] = Math.max(a[ 1 ], dp[ 0 ]); } else if (n >= 3 ) { // Either select the first // element or don't dp[ 0 ] = Math.max( 0 , a[ 0 ]); // Either select the first or the second element // or don't select any element dp[ 1 ] = Math.max(a[ 1 ], Math.max( 0 , a[ 0 ])); // Either select first, second, third or nothing dp[ 2 ] = Math.max(a[ 2 ], Math.max(a[ 1 ], Math.max( 0 , a[ 0 ]))); int i = 3 ; // For the rest of the elements while (i < n) { // Either select the best sum till // previous_index or select the current // element + best_sum till index-3 dp[i] = Math.max(dp[i - 1 ], a[i] + dp[i - 3 ]); i++; } } return dp[n - 1 ]; } // Driver code public static void main(String[] args) { int arr[] = { 1 , 2 , - 2 , 4 , 3 }; int n = arr.length; System.out.println(max_sum(arr, n)); } } // This code is contributed by Rajput-Ji |
Python3
# Python3 implementation of the approach # Function to return the maximum sum # of the sub-sequence such that two # consecutive elements have a difference of # at least 3 in their indices # in the given array def max_sum(a, n) : dp = [ 0 ] * n; # If there is a single element in the array if (n = = 1 ) : # Either select it or don't dp[ 0 ] = max ( 0 , a[ 0 ]); # If there are two elements elif (n = = 2 ) : # Either select the first # element or don't dp[ 0 ] = max ( 0 , a[ 0 ]); # Either select the first or the second element # or don't select any element dp[ 1 ] = max (a[ 1 ], dp[ 0 ]); elif (n > = 3 ) : # Either select the first # element or don't dp[ 0 ] = max ( 0 , a[ 0 ]); # Either select the first or the second element # or don't select any element dp[ 1 ] = max (a[ 1 ], max ( 0 , a[ 0 ])); # Either select first, second, third or nothing dp[ 2 ] = max (a[ 2 ], max (a[ 1 ], max ( 0 , a[ 0 ]))); i = 3 ; # For the rest of the elements while (i < n) : # Either select the best sum till # previous_index or select the current # element + best_sum till index-3 dp[i] = max (dp[i - 1 ], a[i] + dp[i - 3 ]); i + = 1 ; return dp[n - 1 ]; # Driver code if __name__ = = "__main__" : arr = [ 1 , 2 , - 2 , 4 , 3 ]; n = len (arr); print (max_sum(arr, n)); # This code is contributed by AnkitRai01 |
C#
// C# implementation of the approach using System; class GFG { // Function to return the maximum sum // of the sub-sequence such that two // consecutive elements have a difference of // at least 3 in their indices // in the given array static int max_sum( int []a, int n) { int []dp = new int [n]; // If there is a single element in the array if (n == 1) { // Either select it or don't dp[0] = Math.Max(0, a[0]); } // If there are two elements else if (n == 2) { // Either select the first // element or don't dp[0] = Math.Max(0, a[0]); // Either select the first or the second element // or don't select any element dp[1] = Math.Max(a[1], dp[0]); } else if (n >= 3) { // Either select the first // element or don't dp[0] = Math.Max(0, a[0]); // Either select the first or the second element // or don't select any element dp[1] = Math.Max(a[1], Math.Max(0, a[0])); // Either select first, second, third or nothing dp[2] = Math.Max(a[2], Math.Max(a[1], Math.Max(0, a[0]))); int i = 3; // For the rest of the elements while (i < n) { // Either select the best sum till // previous_index or select the current // element + best_sum till index-3 dp[i] = Math.Max(dp[i - 1], a[i] + dp[i - 3]); i++; } } return dp[n - 1]; } // Driver code static public void Main () { int []arr = { 1, 2, -2, 4, 3 }; int n = arr.Length; Console.Write(max_sum(arr, n)); } } // This code is contributed by ajit.. |
Javascript
<script> // Javascript implementation of the approach // Function to return the maximum sum // of the sub-sequence such that two // consecutive elements have a difference of // at least 3 in their indices // in the given array function max_sum(a, n) { let dp = new Array(n); // If there is a single element in the array if (n == 1) { // Either select it or don't dp[0] = Math.max(0, a[0]); } // If there are two elements else if (n == 2) { // Either select the first // element or don't dp[0] = Math.max(0, a[0]); // Either select the first or the second element // or don't select any element dp[1] = Math.max(a[1], dp[0]); } else if (n >= 3) { // Either select the first // element or don't dp[0] = Math.max(0, a[0]); // Either select the first or the second element // or don't select any element dp[1] = Math.max(a[1], Math.max(0, a[0])); // Either select first, second, third or nothing dp[2] = Math.max(a[2], Math.max(a[1], Math.max(0, a[0]))); let i = 3; // For the rest of the elements while (i < n) { // Either select the best sum till // previous_index or select the current // element + best_sum till index-3 dp[i] = Math.max(dp[i - 1], a[i] + dp[i - 3]); i++; } } return dp[n - 1]; } let arr = [ 1, 2, -2, 4, 3 ]; let n = arr.length; document.write(max_sum(arr, n)); </script> |
5
Time Complexity: O(N)
Auxiliary Space: O(N)bb
Efficient approach : Space optimization O(1)
To optimize the space complexity of the previous code. Since we only use the values of the previous three elements to compute the value of the current element in the dp array, we can replace the dp array with three variables to keep track of the maximum sum till the previous three indices. This way, we can reduce the space complexity from O(n) to O(1).
Implementation Steps:
- Initialize three variables prev_3, prev_2, and prev_1 to the maximum of 0 and the first, second, and third elements of the input array, respectively. Also, initialize a variable curr to 0.
- Iterate over the remaining elements of the input array from index 3 to n-1.
- Now calculate curr from previous computations.
- Update the variables prev_3, prev_2, prev_1 for further iterations.
- After iterating over all the elements, return the value of curr as the maximum sum of the sub-sequence.
Implementation:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to return the maximum sum // of the sub-sequence such that two // consecutive elements have a difference of // at least 3 in their indices // in the given array int max_sum( int a[], int n) { // create variables to keep track of previous computations int prev_3 = max(0, a[0]); int prev_2 = max(a[1], max(0, a[0])); int prev_1 = max(a[2], max(a[1], max(0, a[0]))); // to store current value int curr = 0; for ( int i = 3; i < n; i++) { curr = max(prev_1, a[i] + prev_3); prev_3 = prev_2; prev_2 = prev_1; prev_1 = curr; } return curr; } // Driver code int main() { int arr[] = { 1, 2, -2, 4, 3 }; int n = sizeof (arr) / sizeof (arr[0]); cout << max_sum(arr, n); return 0; } |
Java
import java.util.*; public class Main { // Function to return the maximum sum // of the sub-sequence such that two // consecutive elements have a difference of // at least 3 in their indices static int max_sum( int [] a, int n) { // create variables to keep track of previous // computations int prev_3 = Math.max( 0 , a[ 0 ]); int prev_2 = Math.max(a[ 1 ], Math.max( 0 , a[ 0 ])); int prev_1 = Math.max( a[ 2 ], Math.max(a[ 1 ], Math.max( 0 , a[ 0 ]))); // to store current value int curr = 0 ; for ( int i = 3 ; i < n; i++) { curr = Math.max(prev_1, a[i] + prev_3); prev_3 = prev_2; prev_2 = prev_1; prev_1 = curr; } return curr; } // Driver code public static void main(String[] args) { int [] arr = { 1 , 2 , - 2 , 4 , 3 }; int n = arr.length; System.out.println(max_sum(arr, n)); } } |
Python3
# Function to return the maximum sum # of the sub-sequence such that two # consecutive elements have a difference of # at least 3 in their indices # in the given array def max_sum(a, n): # create variables to keep track of previous computations prev_3 = max ( 0 , a[ 0 ]) prev_2 = max (a[ 1 ], max ( 0 , a[ 0 ])) prev_1 = max (a[ 2 ], max (a[ 1 ], max ( 0 , a[ 0 ]))) # to store current value curr = 0 for i in range ( 3 , n): curr = max (prev_1, a[i] + prev_3) prev_3 = prev_2 prev_2 = prev_1 prev_1 = curr return curr arr = [ 1 , 2 , - 2 , 4 , 3 ] n = len (arr) print (max_sum(arr, n)) |
C#
using System; class MainClass { // Function to return the maximum sum // of the sub-sequence such that two // consecutive elements have a difference of // at least 3 in their indices // in the given array public static int max_sum( int [] a, int n) { // create variables to keep track of previous // computations int prev_3 = Math.Max(0, a[0]); int prev_2 = Math.Max(a[1], Math.Max(0, a[0])); int prev_1 = Math.Max( a[2], Math.Max(a[1], Math.Max(0, a[0]))); // to store current value int curr = 0; for ( int i = 3; i < n; i++) { curr = Math.Max(prev_1, a[i] + prev_3); prev_3 = prev_2; prev_2 = prev_1; prev_1 = curr; } return curr; } // Driver code public static void Main() { int [] arr = { 1, 2, -2, 4, 3 }; int n = arr.Length; Console.WriteLine(max_sum(arr, n)); } } |
Javascript
function maxSum(a, n) { let prev_3 = Math.max(0, a[0]); let prev_2 = Math.max(a[1], Math.max(0, a[0])); let prev_1 = Math.max(a[2], Math.max(a[1], Math.max(0, a[0]))); let curr = 0; for (let i = 3; i < n; i++) { curr = Math.max(prev_1, a[i] + prev_3); prev_3 = prev_2; prev_2 = prev_1; prev_1 = curr; } return curr; } const arr = [1, 2, -2, 4, 3]; const n = arr.length; console.log(maxSum(arr, n)); |
Output:
5
Time Complexity: O(N)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!