Given two arrays arr[] and brr[] of size N such that the array brr[] consists of scores associated with corresponding elements of the array arr[]. The task is to find the maximum possible sum of assigned scores of a subsequence of numerically consecutive and distinct elements of the array arr[].
Examples:
Input: arr[] = {1, 2, 3, 3, 3, 1}, brr[] = {-1, 2, 10, 20, -10, -9}Â
Output: 22Â
Explanation:Â
Distinct values from the array = {1, 2, 3}Â
Maximum value assigned to each element = {1: -1, 2: 2, 3: 20}Â
Select the elements at index 2 and 4 in arr[] which are {2, 3}.Â
Maximum score = 2 + 20 = 22.Input: arr[] = {1, 2, 3, 2, 3, 1}, brr[] = {-1, 2, 10, 20, -10, -9}Â
Output: 32Â
Explanation: Selected subsequence is {arr[1], arr[2], arr[3]} = {2, 3, 2}
Naive Approach: The simplest approach to solve the problem is to use recursion. Follow the steps below to solve the problem:
- Generate all possible subsets of the given array arr[] such that the subset has unique and consecutive elements.
- While generating the subsets in the above step, there are two possibilities for every element of either being added to the subsequence or not. Therefore, follow the steps:Â
- If the current element is differed by 1 from the previously selected element, add the element to the subsequence.
- Otherwise, proceed to the next element.
- Update the maximum_score by considering both the above two possibilities.
- Print the final value of maximum_score obtained after the complete traversal of the array.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;  // Function to find the maximum score// with unique element in the subsetint maximumSum(int a[], int b[], int n,                int index, int lastpicked){         // Base Case    if (index == n)        return 0;      int option1 = 0, option2 = 0;      // Check if the previously picked    // element differs by 1 from the    // current element    if (lastpicked == -1 ||       a[lastpicked] != a[index])          // Calculate score by including        // the current element        option1 = b[index] + maximumSum(                             a, b, n,                             index + 1,                             index);      // Calculate score by excluding    // the current element    option2 = maximumSum(a, b, n,                         index + 1,                         lastpicked);      // Return maximum of the    // two possibilities    return max(option1, option2);}  // Driver codeint main(){         // Given arrays    int arr[] = { 1, 2, 3, 3, 3, 1 };    int brr[] = { -1, 2, 10, 20, -10, -9 };         int N = sizeof(arr) / sizeof(arr[0]);         // Function call    cout << (maximumSum(arr, brr, N, 0, -1));}Â
// This code is contributed by rutvik_56 |
Java
// Java program for the above approachimport java.io.*;Â
class GFG {Â
    // Function to find the maximum score    // with unique element in the subset    public static int maximumSum(        int[] a, int[] b, int n, int index,        int lastpicked)    {        // Base Case        if (index == n)            return 0;Â
        int option1 = 0, option2 = 0;Â
        // Check if the previously picked        // element differs by 1 from the        // current element        if (lastpicked == -1            || a[lastpicked] != a[index])Â
            // Calculate score by including            // the current element            option1                = b[index]                  + maximumSum(a, b, n,                               index + 1,                               index);Â
        // Calculate score by excluding        // the current element        option2 = maximumSum(a, b, n,                             index + 1,                             lastpicked);Â
        // Return maximum of the        // two possibilities        return Math.max(option1, option2);    }Â
    // Driver Code    public static void main(String[] args)    {        // Given arrays        int arr[] = { 1, 2, 3, 3, 3, 1 };        int brr[] = { -1, 2, 10, 20, -10, -9 };Â
        int N = arr.length;Â
        // Function Call        System.out.println(            maximumSum(arr, brr,                       N, 0, -1));    }} |
Python3
# Python3 program for the above approachÂ
# Function to find the maximum score# with unique element in the subsetdef maximumSum(a, b, n, index, lastpicked):         # Base Case    if (index == n):        return 0Â
    option1 = 0    option2 = 0Â
    # Check if the previously picked    # element differs by 1 from the    # current element    if (lastpicked == -1 or      a[lastpicked] != a[index]):Â
        # Calculate score by including        # the current element        option1 = b[index] + maximumSum(a, b, n,                                         index + 1,                                        index)Â
    # Calculate score by excluding    # the current element    option2 = maximumSum(a, b, n, index + 1,                          lastpicked)Â
# Return maximum of the# two possibilities    return max(option1, option2)Â
# Driver Codeif __name__ == '__main__':         # Given arrays    arr = [ 1, 2, 3, 3, 3, 1 ]    brr = [ -1, 2, 10, 20, -10, -9 ]Â
    N = len(arr)Â
    # Function call    print(maximumSum(arr, brr, N, 0, -1))Â
# This code is contributed by mohit kumar 29 |
C#
// C# program for // the above approachusing System;class GFG{Â
// Function to find the maximum score// with unique element in the subsetpublic static int maximumSum(int[] a, int[] b,                              int n, int index,                              int lastpicked){  // Base Case  if (index == n)    return 0;Â
  int option1 = 0, option2 = 0;Â
  // Check if the previously picked  // element differs by 1 from the  // current element  if (lastpicked == -1 ||       a[lastpicked] != a[index])Â
    // Calculate score by including    // the current element    option1 = b[index] + maximumSum(a, b, n,                                     index + 1,                                     index);Â
  // Calculate score by excluding  // the current element  option2 = maximumSum(a, b, n,                       index + 1,                       lastpicked);Â
  // Return maximum of the  // two possibilities  return Math.Max(option1, option2);}   Â
// Driver Codepublic static void Main(String[] args){  // Given arrays  int []arr = {1, 2, 3, 3, 3, 1};  int []brr = {-1, 2, 10, 20, -10, -9};Â
  int N = arr.Length;Â
  // Function Call  Console.WriteLine(maximumSum(arr, brr,                                N, 0, -1));}}Â
// This code is contributed by shikhasingrajput |
Javascript
<script>Â
// JavaScript program to implement// the above approachÂ
    // Function to find the maximum score    // with unique element in the subset    function maximumSum(        a, b, n, index,        lastpicked)    {        // Base Case        if (index == n)            return 0;          let option1 = 0, option2 = 0;          // Check if the previously picked        // element differs by 1 from the        // current element        if (lastpicked == -1            || a[lastpicked] != a[index])              // Calculate score by including            // the current element            option1                = b[index]                  + maximumSum(a, b, n,                               index + 1,                               index);          // Calculate score by excluding        // the current element        option2 = maximumSum(a, b, n,                             index + 1,                             lastpicked);          // Return maximum of the        // two possibilities        return Math.max(option1, option2);    }  // Driver codeÂ
        // Given arrays        let arr = [ 1, 2, 3, 3, 3, 1 ];        let brr = [ -1, 2, 10, 20, -10, -9 ];          let N = arr.length;          // Function Call        document.write(            maximumSum(arr, brr,                       N, 0, -1));Â
// This code is contributed by target_2.</script> |
22
Time Complexity: O(2N)Â
Auxiliary Space: O(2N)
Efficient Approach: The above approach can be optimized by using Dynamic Programming as the problem has Overlapping Subproblems. Below are the steps:
- Initialize index as 0 and lastPicked as -1.
- Initialize a 2D array say dp[][] to store the result of the subproblems.
- The states of dp[][] will be the current index and last picked integer.
- Calculate the score for both possible options:Â
- Select the current element if the last picked integer is different from the current integer.
- Skip the current element and move on to the next element.
- Store the current state as the maximum of the value calculated above two-state.
- Print the value of dp[index][lastPicked + 1] as the result after all the recursive calls end.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to find the maximum// score possibleint maximumSum(int a[], int b[], int n,                int index, int lastpicked,               vector<vector<int>> dp){         // Base Case    if (index == n)        return 0;Â
    // If previously occurred subproblem    // occurred    if (dp[index][lastpicked + 1] != -1)        return dp[index][lastpicked + 1];Â
    int option1 = 0, option2 = 0;Â
    // Check if lastpicked element differs    // by 1 from the current element    if (lastpicked == -1 ||       a[lastpicked] != a[index])     {                 // Calculate score by including        // the current element        option1 = b[index] + maximumSum(a, b, n,                                        index + 1,                                        index, dp);    }Â
    // Calculate score by excluding    // the current element    option2 = maximumSum(a, b, n,                         index + 1,                         lastpicked, dp);Â
    // Return maximum score from    // the two possibilities    return dp[index][lastpicked + 1] = max(option1,                                            option2);}Â
// Function to print maximum scorevoid maximumPoints(int arr[], int brr[], int n){Â Â Â Â int index = 0, lastPicked = -1;Â
    // DP array to store results    // Initialise dp with -1    vector<vector<int>> dp(n + 5, vector<int>(n + 5, -1));Â
    // Function call    cout << maximumSum(arr, brr, n, index,                       lastPicked, dp)          << endl;}  // Driver code   int main(){         // Given arrays    int arr[] = { 1, 2, 3, 3, 3, 1 };    int brr[] = { -1, 2, 10, 20, -10, -9 };Â
    int N = sizeof(arr) / sizeof(arr[0]);Â
    // Function call    maximumPoints(arr, brr, N);Â
   return 0;}Â
// This code is contributed by divyeshrabadiya07 |
Java
// Java program for the above approachimport java.util.*;Â
class GFG {Â
    // Function to find the maximum    // score possible    public static int maximumSum(        int[] a, int[] b, int n, int index,        int lastpicked, int[][] dp)    {        // Base Case        if (index == n)            return 0;Â
        // If previously occurred subproblem        // occurred        if (dp[index][lastpicked + 1] != -1)            return dp[index][lastpicked + 1];Â
        int option1 = 0, option2 = 0;Â
        // Check if lastpicked element differs        // by 1 from the current element        if (lastpicked == -1            || a[lastpicked] != a[index]) {Â
            // Calculate score by including            // the current element            option1 = b[index]                      + maximumSum(a, b, n,                                   index + 1,                                   index, dp);        }Â
        // Calculate score by excluding        // the current element        option2 = maximumSum(a, b, n,                             index + 1,                             lastpicked, dp);Â
        // Return maximum score from        // the two possibilities        return dp[index][lastpicked + 1]            = Math.max(option1, option2);    }Â
    // Function to print maximum score    public static void maximumPoints(        int arr[], int brr[], int n)    {        int index = 0, lastPicked = -1;Â
        // DP array to store results        int dp[][] = new int[n + 5][n + 5];Â
        // Initialise dp with -1        for (int i[] : dp)            Arrays.fill(i, -1);Â
        // Function call        System.out.println(            maximumSum(arr, brr, n,                       index, lastPicked, dp));    }Â
    // Driver Code    public static void main(String[] args)    {        // Given arrays        int arr[] = { 1, 2, 3, 3, 3, 1 };        int brr[] = { -1, 2, 10, 20, -10, -9 };Â
        int N = arr.length;Â
        // Function Call        maximumPoints(arr, brr, N);    }} |
Python3
# Python3 program for # the above approachÂ
# Function to find the # maximum score possibledef maximumSum(a, b, n, index,               lastpicked, dp):Â
    # Base Case    if (index == n):        return 0Â
    # If previously occurred     # subproblem occurred    if (dp[index][lastpicked + 1] != -1):        return dp[index][lastpicked + 1]Â
    option1, option2 = 0, 0Â
    # Check if lastpicked element differs    # by 1 from the current element    if (lastpicked == -1 or        a[lastpicked] != a[index]):Â
        # Calculate score by including        # the current element        option1 = (b[index] +                   maximumSum(a, b, n,                               index + 1,                               index, dp))        # Calculate score by excluding    # the current element    option2 = maximumSum(a, b, n,                          index + 1,                          lastpicked, dp)Â
    # Return maximum score from    # the two possibilities    dp[index][lastpicked + 1] = max(option1,                                     option2)    return dp[index][lastpicked + 1]Â
# Function to print maximum scoredef maximumPoints(arr, brr, n):Â
    index = 0    lastPicked = -1Â
    # DP array to store results    dp =[[ -1 for x in range (n + 5)]              for y in range (n + 5)]Â
    # Function call    print (maximumSum(arr, brr,                       n, index,                       lastPicked, dp))Â
# Driver Codeif __name__ == "__main__":       # Given arrays    arr = [1, 2, 3, 3, 3, 1]    brr = [-1, 2, 10, 20, -10, -9]Â
    N = len(arr)Â
    # Function Call    maximumPoints(arr, brr, N)Â
# This code is contributed by Chitranayal |
C#
// C# program for // the above approachusing System;class GFG{Â
// Function to find the maximum// score possiblepublic static int maximumSum(int[] a, int[] b,                              int n, int index,                             int lastpicked,                              int[,] dp){  // Base Case  if (index == n)    return 0;Â
  // If previously occurred   // subproblem occurred  if (dp[index, lastpicked + 1] != -1)    return dp[index, lastpicked + 1];Â
  int option1 = 0, option2 = 0;Â
  // Check if lastpicked element differs  // by 1 from the current element  if (lastpicked == -1 ||       a[lastpicked] != a[index])   {    // Calculate score by including    // the current element    option1 = b[index] + maximumSum(a, b, n,                                    index + 1,                                    index, dp);  }Â
  // Calculate score by excluding  // the current element  option2 = maximumSum(a, b, n,                       index + 1,                       lastpicked, dp);Â
  // Return maximum score from  // the two possibilities  return dp[index, lastpicked + 1] =          Math.Max(option1, option2);}Â
// Function to print maximum scorepublic static void maximumPoints(int []arr, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int []brr, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int n){Â Â int index = 0, lastPicked = -1;Â
  // DP array to store results  int [,]dp = new int[n + 5, n + 5];Â
  // Initialise dp with -1  for(int i = 0; i < n + 5; i++)  {    for (int j = 0; j < n + 5; j++)     {      dp[i, j] = -1;    }  }  // Function call  Console.WriteLine(maximumSum(arr, brr, n,                               index, lastPicked,                                dp));}Â
// Driver Codepublic static void Main(String[] args){  // Given arrays  int []arr = {1, 2, 3, 3, 3, 1};  int []brr = {-1, 2, 10, 20, -10, -9};Â
  int N = arr.Length;Â
  // Function Call  maximumPoints(arr, brr, N);}}Â
// This code is contributed by Rajput-Ji |
Javascript
<script>Â
// JavaScript program for the above approachÂ
    // Function to find the maximum    // score possible    function maximumSum(        a, b, n, index,        lastpicked, dp)    {        // Base Case        if (index == n)            return 0;          // If previously occurred subproblem        // occurred        if (dp[index][lastpicked + 1] != -1)            return dp[index][lastpicked + 1];          let option1 = 0, option2 = 0;          // Check if lastpicked element differs        // by 1 from the current element        if (lastpicked == -1            || a[lastpicked] != a[index]) {              // Calculate score by including            // the current element            option1 = b[index]                      + maximumSum(a, b, n,                                   index + 1,                                   index, dp);        }          // Calculate score by excluding        // the current element        option2 = maximumSum(a, b, n,                             index + 1,                             lastpicked, dp);          // Return maximum score from        // the two possibilities        return dp[index][lastpicked + 1]            = Math.max(option1, option2);    }      // Function to print maximum score    function maximumPolets(        arr, brr, n)    {        let index = 0, lastPicked = -1;          // DP array to store results        let dp = new Array(n + 5);        // Loop to create 2D array using 1D array        for (var i = 0; i < dp.length; i++) {            dp[i] = new Array(2);        }          // Initialise dp with -1        for (var i = 0; i < dp.length; i++) {            for (var j = 0; j < dp.length; j++) {            dp[i][j] = -1;        }        }          // Function call        document.write(            maximumSum(arr, brr, n,                       index, lastPicked, dp));    }  // Driver CodeÂ
   // Given arrays        let arr = [ 1, 2, 3, 3, 3, 1 ];        let brr = [ -1, 2, 10, 20, -10, -9 ];          let N = arr.length;          // Function Call        maximumPolets(arr, brr, N);           </script> |
22
Time Complexity: O(N2)Â
Auxiliary Space: O(N2)
Efficient approach : Using DP Tabulation method ( Iterative approach )
The approach to solve this problem is same but DP tabulation(bottom-up) method is better then Dp + memoization(top-down) because memoization method needs extra stack space of recursion calls.
Steps to solve this problem :
- Create a table DP to store the solution of the subproblems and initialize it with 0.
- Initialize the table with base cases.
- Now Iterate over subproblems to get the value of current problem form previous computation of subproblems stored in DP.
- Initialize a variable maxScore with 0 because it compare and store maximum value.
- Now iterate over dp and get the maximum value and store it in maxScore.
- At last print the final solution stored in maxScore.
Implementation :
C++
// C++ program for above approach#include <bits/stdc++.h>using namespace std;Â
// Function to find the maximum score possiblevoid maximumPoints(int arr[], int brr[], int n){    // DP table to store results    int dp[n + 5][n + 5];Â
    // Initialise DP table with 0    memset(dp, 0, sizeof(dp));Â
    // Loop through all indices and their previous index    for (int i = 1; i <= n; i++) {        for (int j = 0; j < i; j++) {            // Check if previous index value differs by 1            if (j == 0 || arr[j - 1] != arr[i - 1]) {                // Calculate score by including current element                dp[i][j] = max(dp[i][j], dp[j][0] + brr[i - 1]);            }            // Calculate score by excluding current element            dp[i][i - 1] = max(dp[i][i - 1], dp[j][i - j - 1]);        }    }Â
    // Find maximum score    int maxScore = 0;    for (int i = 0; i <= n; i++) {        for (int j = 0; j <= n; j++) {            maxScore = max(maxScore, dp[i][j]);        }    }Â
    // Print maximum score    cout << maxScore << endl;}Â
// Driver codeint main(){    // Given arrays    int arr[] = { 1, 2, 3, 3, 3, 1 };    int brr[] = { -1, 2, 10, 20, -10, -9 };Â
    int N = sizeof(arr) / sizeof(arr[0]);Â
    // Function call    maximumPoints(arr, brr, N);Â
    return 0;}// this code is contributed by bhardwajji |
Python3
# Function to find the maximum score possibledef maximumPoints(arr, brr, n):    # DP table to store results    dp = [[0 for j in range(n + 5)] for i in range(n + 5)]Â
    # Loop through all indices and their previous index    for i in range(1, n + 1):        for j in range(i):            # Check if previous index value differs by 1            if j == 0 or arr[j - 1] != arr[i - 1]:                # Calculate score by including current element                dp[i][j] = max(dp[i][j], dp[j][0] + brr[i - 1])            # Calculate score by excluding current element            dp[i][i - 1] = max(dp[i][i - 1], dp[j][i - j - 1])Â
    # Find maximum score    maxScore = 0    for i in range(n + 1):        for j in range(n + 1):            maxScore = max(maxScore, dp[i][j])Â
    # Print maximum score    print(maxScore)Â
Â
# Given arraysarr = [1, 2, 3, 3, 3, 1]brr = [-1, 2, 10, 20, -10, -9]N = len(arr)Â
# Function callmaximumPoints(arr, brr, N) |
C#
using System;Â
public class Program {Â
  // Function to find the maximum score possible  public static void MaximumPoints(int[] arr, int[] brr,                                   int n)  {    // DP table to store results    int[, ] dp = new int[n + 5, n + 5];Â
    // Initialise DP table with 0    for (int i = 0; i < n + 5; i++) {      for (int j = 0; j < n + 5; j++) {        dp[i, j] = 0;      }    }Â
    // Loop through all indices and their previous index    for (int i = 1; i <= n; i++) {      for (int j = 0; j < i; j++) {Â
        // Check if previous index value differs by        // 1        if (j == 0 || arr[j - 1] != arr[i - 1]) {Â
          // Calculate score by including current          // element          dp[i, j] = Math.Max(            dp[i, j], dp[j, 0] + brr[i - 1]);        }        // Calculate score by excluding current        // element        dp[i, i - 1] = Math.Max(dp[i, i - 1],                                dp[j, i - j - 1]);      }    }Â
    // Find maximum score    int maxScore = 0;    for (int i = 0; i <= n; i++) {      for (int j = 0; j <= n; j++) {        maxScore = Math.Max(maxScore, dp[i, j]);      }    }Â
    // Print maximum score    Console.WriteLine(maxScore);  }Â
  // Driver code  public static void Main()  {    // Given arrays    int[] arr = { 1, 2, 3, 3, 3, 1 };    int[] brr = { -1, 2, 10, 20, -10, -9 };Â
    int n = arr.Length;Â
    // Function call    MaximumPoints(arr, brr, n);  }}Â
// This code is contritbuted by sarojmcy2e |
Javascript
function maximumPoints(arr, brr, n) {    // DP table to store results    const dp = Array.from({        length: n + 5    }, () => Array(n + 5).fill(0));Â
    // Loop through all indices and their previous index    for (let i = 1; i <= n; i++) {        for (let j = 0; j < i; j++) {            // Check if previous index value differs by 1            if (j === 0 || arr[j - 1] !== arr[i - 1]) {                // Calculate score by including current element                dp[i][j] = Math.max(dp[i][j], dp[j][0] + brr[i - 1]);            }            // Calculate score by excluding current element            dp[i][i - 1] = Math.max(dp[i][i - 1], dp[j][i - j - 1]);        }    }Â
    // Find maximum score    let maxScore = 0;    for (let i = 0; i <= n; i++) {        for (let j = 0; j <= n; j++) {            maxScore = Math.max(maxScore, dp[i][j]);        }    }Â
    // Print maximum score    console.log(maxScore);}Â
// Given arraysconst arr = [1, 2, 3, 3, 3, 1];const brr = [-1, 2, 10, 20, -10, -9];const n = arr.length;Â
// Function callmaximumPoints(arr, brr, n);Â
// This code is contributed by user_dtewbxkn77n |
Java
import java.util.*;Â
class Main {    // Function to find the maximum score possible    static void maximumPoints(int arr[], int brr[], int n)    {        // DP table to store results        int dp[][] = new int[n + 5][n + 5];Â
        // Initialise DP table with 0        for (int i = 0; i < n + 5; i++) {            Arrays.fill(dp[i], 0);        }Â
        // Loop through all indices and      //their previous index        for (int i = 1; i <= n; i++) {            for (int j = 0; j < i; j++) {                               // Check if previous index              // value differs by 1                if (j == 0 || arr[j - 1] != arr[i - 1]) {                                       // Calculate score by including                    // the current element                    dp[i][j] = Math.max(                        dp[i][j], dp[j][0] + brr[i - 1]);                }                // Calculate score by excluding                // current element                dp[i][i - 1] = Math.max(dp[i][i - 1],                                        dp[j][i - j - 1]);            }        }Â
        // Find maximum score        int maxScore = 0;        for (int i = 0; i <= n; i++) {            for (int j = 0; j <= n; j++) {                maxScore = Math.max(maxScore, dp[i][j]);            }        }Â
        // Print maximum score        System.out.println(maxScore);    }Â
    // Driver Code    public static void main(String[] args)    {        int arr[] = { 1, 2, 3, 3, 3, 1 };        int brr[] = { -1, 2, 10, 20, -10, -9 };        int N = arr.length;        maximumPoints(arr, brr, N);    }} |
22
Time Complexity: O(N*N)Â
Auxiliary Space: O(N*N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

… [Trackback]
[…] Info on that Topic: geeksforgeeks.org/maximum-score-assigned-to-a-subsequence-of-numerically-consecutive-and-distinct-array-elements/ […]