1695. Maximum Erasure Value #1956
-
Topics: You are given an array of positive integers Return the maximum score you can get by erasing exactly one subarray. An array Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the maximum sum of a contiguous subarray where all elements are unique. The solution involves efficiently scanning the array while maintaining a sliding window that ensures all elements within the window are distinct. Approach
This approach efficiently processes the array in O(n) time with O(1) space for the frequency array (since the maximum value of elements is constrained to Let's implement this solution in PHP: 1695. Maximum Erasure Value <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function maximumUniqueSubarray($nums) {
$n = count($nums);
$max_sum = 0;
$current_sum = 0;
$freq = array_fill(0, 10001, 0);
$left = 0;
for ($right = 0; $right < $n; $right++) {
$num = $nums[$right];
$current_sum += $num;
$freq[$num]++;
while ($freq[$num] > 1) {
$left_num = $nums[$left];
$current_sum -= $left_num;
$freq[$left_num]--;
$left++;
}
if ($current_sum > $max_sum) {
$max_sum = $current_sum;
}
}
return $max_sum;
}
// Test cases
$nums1 = array(4, 2, 4, 5, 6);
echo maximumUniqueSubarray($nums1) . "\n"; // Output: 17
$nums2 = array(5, 2, 1, 2, 5, 2, 1, 2, 5);
echo maximumUniqueSubarray($nums2) . "\n"; // Output: 8
?> Explanation:
This approach efficiently processes the array in linear time, making it optimal for large input sizes as specified in the problem constraints. |
Beta Was this translation helpful? Give feedback.
We need to find the maximum sum of a contiguous subarray where all elements are unique. The solution involves efficiently scanning the array while maintaining a sliding window that ensures all elements within the window are distinct.
Approach
left
andright
, to represent the current window of elements. Theright
pointer expands the window by including new elements, while theleft
pointer contracts the window when a duplicate element is encountered.