GeeksforGeeks App
Open App
Browser
Continue

Maximize sum of selected integers from an Array of pair of integers as per given condition

Given an array arr[] having N pair of integers of the form (x, y), the task is to maximize the sum y values in selected pairs such that if a pair (xi, yi) is selected, the next xi pairs cannot be selected.

Examples:

Input: arr[]= {{1, 5}, {2, 7}, {1, 4}, {1, 5}, {1, 10}}
Output: 19
Explanation: Choose the pair at the index i = 0 i.e, (1, 5). Hence the next 1 pair cannot be selected. Similarly, select the pairs at index 2 and 4 i.e, (1, 4) and (1, 10). Therefore, the sum of all the y values of the selected pairs is 5+4+10 = 19, which is the maximum possible.

Input: arr[] = {{1, 5}, {2, 10}, {3, 3}, {7, 4}}
Output: 10

Recursive Approach:

We start with the first element of the array, and for each element, we have two choices: either we select it or we don’t select it. If we select an element, we cannot select its adjacent element. Therefore, we skip the next element and recursively call the function for the remaining elements. If we don’t select an element, we move on to the next element and recursively call the function for the remaining elements.

The base case for this recursion is when we reach the end of the array. If we have reached the end of the array, we return 0. Otherwise, we compare the maximum sum we get if we select the current element with the maximum sum we get if we don’t select the current element, and we return the larger of the two.

Algorithm:

1. Initialize an integer n with the size of the input array.
2. Define a recursive function solve that takes three parameters: the input array arr, the current index idx, and the size of the input array n.
3. In the solve function, check if the current index idx is greater than or equal to n. If it is, return 0.
4. If the current index is n-1, return the y value of the pair.
5. Calculate the maximum possible sum for the current index using the recurrence relation:
ans = max(solve(arr, idx + 1, n), solve(arr, idx + arr[idx].first + 1, n) + arr[idx].second)
6. Return the value of ans.
7. Call the solve function with arr, 0, and n as arguments and store the result in ans.
8. Output the result.

Below is the implementation of the approach:

C++

 `// C++ code for the approach` `#include ``using` `namespace` `std;` `// Function to calculate the maximum possible sum``// of selected elements of the array arr[] using DP``int` `solve(vector>& arr, ``int` `idx, ``int` `n)``{``    ``// If the current index is greater than or equal to n,``    ``// return 0``    ``if` `(idx >= n) {``        ``return` `0;``    ``}` `    ``// If the current index is n-1, return the y value of``    ``// the pair``    ``if` `(idx == n - 1)``        ``return` `arr[n - 1].second;` `    ``// Calculate the maximum possible sum for the current``    ``// index``    ``int` `ans``        ``= max(solve(arr, idx + 1, n),``              ``solve(arr, idx + arr[idx].first + 1, n)``                  ``+ arr[idx].second);` `    ``// Return the value of ans``    ``return` `ans;``}` `// Driver's code``int` `main()``{``    ``// Given array``    ``vector> arr = {``        ``{ 1, 5 }, { 2, 7 }, { 1, 4 }, { 1, 5 }, { 1, 10 }``    ``};` `    ``// Length of the array``    ``int` `N = arr.size();` `    ``// Call solve function and store the result in ans``    ``int` `ans = solve(arr, 0, N);` `    ``// Output the result``    ``cout << ans << endl;` `    ``// Return 0 to indicate success``    ``return` `0;``}` `// This code is contributed by Chandramani Kumar`

Output

`19`

Time Complexity: O(2^n), since for each element, we are considering two possibilities – either include it in the sum or exclude it from the sum. Since there are n elements, the total number of possible combinations is 2^n.

Auxiliary Space: O(n), since we are only using the call stack space to store the function calls. The maximum depth of the call stack will be n, since we are recursively calling the function for each element of the array.

Memoised Approach:

This approach uses memoised method of dynamic programming to solve the given problem. We first initialize a 1D array dp[] with 0, which stores the maximum possible sum of selected y values for each index i.

We then compute the value of dp[i] for all i in the range [n, 0] by considering two choices:

1. Either we skip the i-th pair and consider the maximum possible sum of selected y values for the remaining pairs (i.e., dp[i+1]),
2. or we select the i-th pair and consider the maximum possible sum of selected y values for the pairs that come after the next x pairs (i.e., dp[i+arr[i].first+1]+arr[i].second).

Finally, we return the value stored in dp[0], which represents the maximum possible sum of selected y values for the entire array arr[].

Algorithm:

1. Initialize an integer n with the size of the input array.
2. Initialize a vector of integers dp of size n with -1 to store the subproblem solutions.
3. Define a recursive function solve that takes four parameters: the input array arr, the DP array dp, the current index idx, and the size of the input array n.
4. In the solve function, check if the current index idx is greater than or equal to n. If it is, return 0.
5. If the current index is n-1, return the y value of the pair.
6. If the value at current index has already been calculated, return the value.
7. Calculate the maximum possible sum for the current index using the recurrence relation:
ans = max(solve(arr, dp, idx + 1, n), solve(arr, dp, idx + arr[idx].first + 1, n) + arr[idx].second)
8. Store the value of ans in dp array.
9. Return the value of ans.
10. Call the solve function with arr, dp, 0, and n as arguments and store the result in ans.
11. Output the result.

Below is the implementation of the approach:

C++

 `// C++ code for the approach` `#include ``using` `namespace` `std;` `// Function to calculate the maximum possible sum``// of selected elements of the array arr[] using DP``int` `solve(vector >& arr, vector<``int``>& dp,``          ``int` `idx, ``int` `n)``{``      ``// If the current index is greater than or equal to n,``      ``// return 0``    ``if` `(idx >= n) {``        ``return` `0;``    ``}` `    ``// If the current index is n-1, return the y value of``    ``// the pair``    ``if` `(idx == n - 1)``        ``return` `arr[n - 1].second;` `    ``// If the value at current index has already been``    ``// calculated, return the value``    ``if` `(dp[idx] != -1) {``        ``return` `dp[idx];``    ``}` `    ``// Calculate the maximum possible sum for the current``    ``// index``    ``int` `ans``        ``= max(solve(arr, dp, idx + 1, n),``              ``solve(arr, dp, idx + arr[idx].first + 1, n)``                  ``+ arr[idx].second);` `    ``// Store the value of ans in dp array``    ``dp[idx] = ans;` `    ``// Return the value of ans``    ``return` `ans;``}` `// Driver's code``int` `main()``{``    ``// Given array``    ``vector > arr = {``        ``{ 1, 5 }, { 2, 7 }, { 1, 4 }, { 1, 5 }, { 1, 10 }``    ``};``  ` `    ``// Length of the array``    ``int` `N = arr.size();` `    ``// Initialize DP array with -1``    ``vector<``int``> dp(N, -1);` `    ``// Call solve function and store the result in ans``    ``int` `ans = solve(arr, dp, 0, N);` `    ``// Output the result``    ``cout << ans << endl;` `    ``// Return 0 to indicate success``    ``return` `0;``}` `// This code is contributed by Chandramani Kumar`

Output

`19`

Time Complexity: O(N) where N is size of input array.
Auxiliary Space: O(N) as vector dp has been created. Here, n is size of input array.

Approach: The given problem can be solved using dynamic programming. Create an array dp[], where dp[i] represents the maximum possible sum of selected elements of the array arr[] in the range [i, N] and initialize the value of all indices with 0. Hence, the dp[] array can be calculated using the below relation:

dp[i] = max( dp[i + 1], dp[i + xi + 1] + yi)

Therefore, calculate the value for each state in dp[i] for all values of i in the range [N, 0]. The value stored at dp[0] will be the required answer.

Below is the implementation of the above approach:

C++

 `// C++ program for the above approach``#include ``using` `namespace` `std;` `// Function to maximize sum of selected``// integers from an array of pair``// of integers as per given condition``int` `maximizeSum(vector > arr, ``int` `N)``{``    ``// Stores the DP states``    ``vector<``int``> dp(N + 1, 0);` `    ``// Initial Condition``    ``dp[N - 1] = arr[N - 1].second;` `    ``// Loop to traverse the array``    ``// in the range (N - 1, 0]``    ``for` `(``int` `i = N - 2; i >= 0; i--) {` `        ``// If it is in range``        ``if` `(i + arr[i].first < N)` `            ``// Calculate dp[i]``            ``dp[i] = max(dp[i + 1],``                        ``dp[i + arr[i].first + 1]``                            ``+ arr[i].second);` `        ``else``            ``dp[i] = dp[i + 1];``    ``}` `    ``// Return Answer``    ``return` `dp[0];``}` `// Driver Code``int` `main()``{``    ``vector > arr = {``        ``{ 1, 5 }, { 2, 7 }, { 1, 4 }, { 1, 5 }, { 1, 10 }``    ``};``    ``cout << maximizeSum(arr, arr.size());` `    ``return` `0;``}`

Java

 `// Java program for the above approach``import` `java.io.*;``import` `java.lang.*;``import` `java.util.*;` `// User defined Pair class``class` `Pair {``  ``int` `first;``  ``int` `second;` `  ``// Constructor``  ``public` `Pair(``int` `first, ``int` `second)``  ``{``    ``this``.first = first;``    ``this``.second = second;``  ``}``}` `class` `GFG {` `  ``// Function to maximize sum of selected``  ``// integers from an array of pair``  ``// of integers as per given condition``  ``static` `int` `maximizeSum(Pair arr[ ], ``int` `N)``  ``{``    ` `    ``// Stores the DP states``    ``int` `dp[] = ``new` `int``[N + ``1``];` `    ``// Initial Condition``    ``dp[N - ``1``] = arr[N - ``1``].second;` `    ``// Loop to traverse the array``    ``// in the range (N - 1, 0]``    ``for` `(``int` `i = N - ``2``; i >= ``0``; i--) {` `      ``// If it is in range``      ``if` `(i + arr[i].first < N)` `        ``// Calculate dp[i]``        ``dp[i] = Math.max(dp[i + ``1``],``                         ``dp[i + arr[i].first + ``1``]``                         ``+ arr[i].second);` `      ``else``        ``dp[i] = dp[i + ``1``];``    ``}` `    ``// Return Answer``    ``return` `dp[``0``];``  ``}` `  ``// Driver Code``  ``public` `static` `void` `main (String[] args)``  ``{``    ``int` `n = ``5``;` `    ``// Array of Pair``    ``Pair arr[] = ``new` `Pair[n];` `    ``arr[``0``] = ``new` `Pair(``1``, ``5``);``    ``arr[``1``] = ``new` `Pair(``2``, ``7``);``    ``arr[``2``] = ``new` `Pair(``1``, ``4``);``    ``arr[``3``] = ``new` `Pair(``1``, ``5``);``    ``arr[``4``] = ``new` `Pair(``1``, ``10``);``    ``System.out.print(maximizeSum(arr, n));``  ``}``}` `// This code is contributed by hrithikgarg03188.`

Python3

 `# Python code for the above approach` `# Function to maximize sum of selected``# integers from an array of pair``# of integers as per given condition``def` `maximizeSum(arr, N):` `    ``# Stores the DP states``    ``dp ``=` `[``0``] ``*` `(N ``+` `1``)` `    ``# Initial Condition``    ``dp[N ``-` `1``] ``=` `arr[N ``-` `1``][``"second"``]` `    ``# Loop to traverse the array``    ``# in the range (N - 1, 0]``    ``for` `i ``in` `range``(N ``-` `2``, ``-``1``, ``-``1``):` `        ``# If it is in range``        ``if` `(i ``+` `arr[i][``"first"``] < N):` `            ``# Calculate dp[i]``            ``dp[i] ``=` `max``(dp[i ``+` `1``],``                        ``dp[i ``+` `arr[i][``"first"``] ``+` `1``]``                        ``+` `arr[i][``"second"``])` `        ``else``:``            ``dp[i] ``=` `dp[i ``+` `1``]` `    ``# Return Answer``    ``return` `dp[``0``]` `# Driver Code``arr ``=` `[{``"first"``: ``1``, ``"second"``: ``5``},``       ``{``"first"``: ``2``, ``"second"``: ``7``},``       ``{``"first"``: ``1``, ``"second"``: ``4``},``       ``{``"first"``: ``1``, ``"second"``: ``5``},``       ``{``"first"``: ``1``, ``"second"``: ``10``}``       ``]` `print``(maximizeSum(arr, ``len``(arr)))` `# This code is contributed by gfgking`

C#

 `// C# program for the above approach` `using` `System;``using` `System.Collections.Generic;`  `// User defined Pair class``class` `Pair {``  ``public` `int` `first;``  ``public` `int` `second;` `  ``// Constructor``  ``public` `Pair(``int` `first, ``int` `second)``  ``{``    ``this``.first = first;``    ``this``.second = second;``  ``}``}`  `public` `class` `GFG {` `  ``// Function to maximize sum of selected``  ``// integers from an array of pair``  ``// of integers as per given condition``  ``static` `int` `maximizeSum(Pair []arr, ``int` `N)``  ``{` `    ``// Stores the DP states``    ``int` `[]dp = ``new` `int``[N + 1];` `    ``// Initial Condition``    ``dp[N - 1] = arr[N - 1].second;` `    ``// Loop to traverse the array``    ``// in the range (N - 1, 0]``    ``for` `(``int` `i = N - 2; i >= 0; i--) {` `      ``// If it is in range``      ``if` `(i + arr[i].first < N)` `        ``// Calculate dp[i]``        ``dp[i] = Math.Max(dp[i + 1],``                         ``dp[i + arr[i].first + 1]``                         ``+ arr[i].second);` `      ``else``        ``dp[i] = dp[i + 1];``    ``}` `    ``// Return Answer``    ``return` `dp[0];``  ``}` `  ``// Driver Code``  ``public` `static` `void` `Main(String[] args)``  ``{``    ``int` `n = 5;` `    ``// Array of Pair``    ``Pair []arr = ``new` `Pair[n];` `    ``arr[0] = ``new` `Pair(1, 5);``    ``arr[1] = ``new` `Pair(2, 7);``    ``arr[2] = ``new` `Pair(1, 4);``    ``arr[3] = ``new` `Pair(1, 5);``    ``arr[4] = ``new` `Pair(1, 10);``    ``Console.Write(maximizeSum(arr, n));``  ``}``}` `// This code is contributed by shikhasingrajput`

Javascript

 ``

Output

`19`

Time Complexity: O(N)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up