
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- if x present in seen, then
- 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
- Related Questions & Answers
- Maximum Erasure Value in C++
- Python program to find the second maximum value in Dictionary
- Program to find maximum possible value of smallest group in Python
- Program to find minimum possible maximum value after k operations in python
- Program to find maximum value by inserting operators in between numbers in Python
- Find maximum value in each sublist in Python
- Program to find out the cells containing maximum value in a matrix in Python
- Program to find maximum width ramp in Python
- Program to find maximum building height in Python
- Program to find maximum equal frequency in Python
- C++ program to find maximum possible value for which XORed sum is maximum
- Type Erasure in Java
- C++ Program to Find Maximum Value of any Algebraic Expression
- C++ program to find out the maximum value of i
- C++ program to find maximum possible value of XORed sum
Advertisements