Program to find maximum additive score by deleting numbers in Python


Suppose we have a list of numbers called nums. Let us consider an operation where we can select a number, then remove it and increase our score by the sum of the number and its two adjacent numbers. If we can perform this operation as many times as we want as long as we do not select the first or the last number in the list. We have to find the maximal score possible.

So, if the input is like nums = [2, 3, 4, 5, 6], then the output will be 39, as we can select 5, then sum will be (4 + 5 + 6) = 15, array will be [2, 3, 4, 6], then select 4, so sum is (3 + 4 + 6) = 13, and array will be [2, 3, 6], select 3, sum will be (2 + 3 + 6) = 11, So total sum is 15 + 13 + 11 = 39

To solve this, we will follow these steps −

  • n := size of nums
  • if n < 3, then:
    • Define one 2D array of size (n + 1) x (n + 1)
  • for initialize len := 3, when len <= n, update (increase len by 1), do −
    • for initialize i := 1, when i + len - 1 <= n, update (increase i by 1), do −
      • r := i + len - 1
      • ans := 0
      • for initialize k := i + 1, when k <= r - 1, update (increase k by 1), do −
        • curr := dp[i, k] + dp[k, r] + nums[k - 1]
        • if curr > ans, then:
      • ans := ans + nums[i - 1] + nums[r - 1]
      • dp[i, r] := ans
  • return dp[1, n]

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int solve(vector<int>& nums) {
      int n = nums.size();
      if (n < 3) return 0;
         vector<vector<int>> dp(n + 1, vector<int>(n + 1));
         for (int len = 3;
            len <= n; ++len) {
               for (int i = 1; i + len - 1 <= n; ++i) {
                  int r = i + len - 1;
                  int ans = 0;
               for (int k = i + 1; k <= r - 1; ++k) {
                  int curr = dp[i][k] + dp[k][r] + nums[k - 1];
                  if (curr > ans)
                     ans = curr;
               }
               ans += nums[i - 1] + nums[r - 1]; dp[i][r] = ans;
         }
      }
      return dp[1][n];
   }
};
int solve(vector<int>& nums) {
   return (new Solution())->solve(nums);
}
main(){
   vector<int> v = {2, 3, 4, 5, 6};
   cout << solve(v);
}

Input

[2, 3, 4, 5, 6]

Output

39

Updated on: 20-Nov-2020

88 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements