|
| 1 | +// Source : https://leetcode.com/problems/maximum-erasure-value/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2021-05-07 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * You are given an array of positive integers nums and want to erase a subarray containing unique |
| 8 | + * elements. The score you get by erasing the subarray is equal to the sum of its elements. |
| 9 | + * |
| 10 | + * Return the maximum score you can get by erasing exactly one subarray. |
| 11 | + * |
| 12 | + * An array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if |
| 13 | + * it is equal to a[l],a[l+1],...,a[r] for some (l,r). |
| 14 | + * |
| 15 | + * Example 1: |
| 16 | + * |
| 17 | + * Input: nums = [4,2,4,5,6] |
| 18 | + * Output: 17 |
| 19 | + * Explanation: The optimal subarray here is [2,4,5,6]. |
| 20 | + * |
| 21 | + * Example 2: |
| 22 | + * |
| 23 | + * Input: nums = [5,2,1,2,5,2,1,2,5] |
| 24 | + * Output: 8 |
| 25 | + * Explanation: The optimal subarray here is [5,2,1] or [1,2,5]. |
| 26 | + * |
| 27 | + * Constraints: |
| 28 | + * |
| 29 | + * 1 <= nums.length <= 10^5 |
| 30 | + * 1 <= nums[i] <= 10^4 |
| 31 | + ******************************************************************************************************/ |
| 32 | + |
| 33 | +class Solution { |
| 34 | +public: |
| 35 | + int maximumUniqueSubarray(vector<int>& nums) { |
| 36 | + //unordered_map<int, int> pos; |
| 37 | + const int NIL = -1; |
| 38 | + int pos[10001]; |
| 39 | + memset(pos, NIL, sizeof(pos)); |
| 40 | + |
| 41 | + int start=0; |
| 42 | + int max_sum =0, sum = 0; |
| 43 | + |
| 44 | + for(int i = 0; i < nums.size(); i++) { |
| 45 | + int n = nums[i]; |
| 46 | + // if find duplicated number |
| 47 | + if ( pos[n] != NIL) { |
| 48 | + max_sum = max(max_sum, sum); |
| 49 | + //remove the previous numbers until to duplicatied position |
| 50 | + for(;start <= pos[n]; start++){ |
| 51 | + sum -= nums[start]; |
| 52 | + pos[nums[start]] = NIL; |
| 53 | + } |
| 54 | + } |
| 55 | + sum += n; |
| 56 | + pos[n] = i; |
| 57 | + } |
| 58 | + max_sum = max( max_sum , sum ); |
| 59 | + return max_sum; |
| 60 | + } |
| 61 | +}; |
0 commit comments