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 −
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))