Program to find maximum erasure value in Python



Suppose we have an array called nums (with positive values only) and we want to erase a subarray containing unique elements. We will get score that is sum of subarray elements. We have to find the maximum score we can get by erasing exactly one subarray.

So, if the input is like nums = [6,3,2,3,6,3,2,3,6], then the output will be 11, because here optimal subarray is either [6,3,2] or [2,3,6], so sum is 11.

To solve this, we will follow these steps −

  • seen := a new map
  • ans := sum := 0
  • l := 0
  • for each index r and value x nums, do
    • if x present in seen, then
      • index := seen[x]
      • while l <= index, do
        • remove seen[nums[l]]
        • sum := sum - nums[l]
        • l := l + 1
    • seen[x] := r
    • sum := sum + x
    • ans := maximum of ans and sum
  • return ans

Example

Let us see the following implementation to get better understanding −

def solve(nums):
   seen = dict()
   ans = sum = 0
   l = 0
   for r, x in enumerate(nums):
      if x in seen:
         index = seen[x]
         while l <= index:
            del seen[nums[l]]
            sum -= nums[l]
            l += 1

      seen[x] = r
      sum += x
      ans = max(ans, sum)
   return ans

nums = [6,3,2,3,6,3,2,3,6]
print(solve(nums))

Input

[6,3,2,3,6,3,2,3,6]

Output

11

Advertisements