|
| 1 | +/** |
| 2 | + * 3487 |
| 3 | + * Maximum Unique Subarray Sum After Deletion |
| 4 | + ** |
| 5 | + * You are given an integer array nums. |
| 6 | + * You are allowed to delete any number of elements |
| 7 | + * from nums without making it empty. |
| 8 | + * |
| 9 | + * After performing the deletions, |
| 10 | + * select a subarray of nums such that: |
| 11 | + * 1. All elements in the subarray are unique. |
| 12 | + * 2. The sum of the elements in the subarray is maximized. |
| 13 | + * |
| 14 | + * Return the maximum sum of such a subarray. |
| 15 | + * |
| 16 | + * Example 1: |
| 17 | + * Input: nums = [1,2,3,4,5] |
| 18 | + * Output: 15 |
| 19 | + * Explanation: |
| 20 | + * Select the entire array without deleting any element |
| 21 | + * to obtain the maximum sum. |
| 22 | + * |
| 23 | + * Example 2: |
| 24 | + * Input: nums = [1,1,0,1,1] |
| 25 | + * Output: 1 |
| 26 | + * Explanation: |
| 27 | + * Delete the element |
| 28 | + * nums[0] == 1, nums[1] == 1, nums[2] == 0, and nums[3] == 1. |
| 29 | + * Select the entire array [1] to obtain the maximum sum. |
| 30 | + * |
| 31 | + * Example 3: |
| 32 | + * Input: nums = [1,2,-1,-2,1,0,-1] |
| 33 | + * Output: 3 |
| 34 | + * Explanation: |
| 35 | + * Delete the elements |
| 36 | + * nums[2] == -1 and nums[3] == -2, |
| 37 | + * and select the subarray [2, 1] from [1, 2, 1, 0, -1] |
| 38 | + * to obtain the maximum sum. |
| 39 | + * |
| 40 | + * Constraints: |
| 41 | + * • 1 <= nums.length <= 100 |
| 42 | + * • -100 <= nums[i] <= 100 |
| 43 | + * |
| 44 | + * Hint 1: |
| 45 | + * If the maximum element in the array is less than zero, |
| 46 | + * the answer is the maximum element. |
| 47 | + * |
| 48 | + * Hint 2: |
| 49 | + * Otherwise, |
| 50 | + * the answer is the sum of all unique values |
| 51 | + * that are greater than or equal to zero. |
| 52 | + ** |
| 53 | + * https://leetcode.com/problems/maximum-unique-subarray-sum-after-deletion/ |
| 54 | +***/ |
| 55 | + |
| 56 | +using System; |
| 57 | + |
| 58 | +namespace Problems; |
| 59 | + |
| 60 | +public class MaximumUniqueSubarraySumAfterDeletion |
| 61 | +{ |
| 62 | + public int MaxSum( int[] nums ) |
| 63 | + { |
| 64 | + bool[] map = new bool[101]; |
| 65 | + |
| 66 | + int sum = 0; |
| 67 | + int max = int.MinValue; |
| 68 | + |
| 69 | + foreach ( int num in nums ) |
| 70 | + { |
| 71 | + if ( num > 0 && !map[num] ) |
| 72 | + { |
| 73 | + map[num] = true; |
| 74 | + sum += num; |
| 75 | + } |
| 76 | + |
| 77 | + max = Math.Max( max, num ); |
| 78 | + } |
| 79 | + |
| 80 | + if ( max < 0 ) |
| 81 | + { |
| 82 | + return max; |
| 83 | + } |
| 84 | + |
| 85 | + return sum; |
| 86 | + } |
| 87 | +} |
0 commit comments