3487. Maximum Unique Subarray Sum After Deletion #1968
-
Topics: You are given an integer array You are allowed to delete any number of elements from
Return the maximum sum of such a subarray. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the maximum sum of a contiguous subarray after deleting any number of elements (without making the array empty) such that all elements in the subarray are unique. The solution leverages the observation that if the maximum element in the array is negative, the answer is simply that maximum element. Otherwise, the solution involves summing all distinct non-negative elements in the array, as these can always be arranged into a contiguous subarray with unique elements after appropriate deletions. Approach
Let's implement this solution in PHP: 3487. Maximum Unique Subarray Sum After Deletion <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function maxSum($nums) {
$max_val = max($nums);
if ($max_val < 0) {
return $max_val;
}
$set = array();
$sum = 0;
foreach ($nums as $num) {
if ($num >= 0 && !isset($set[$num])) {
$set[$num] = true;
$sum += $num;
}
}
return $sum;
}
// Test cases
echo maxSum([1, 2, 3, 4, 5]) . "\n"; // Output: 15
echo maxSum([1, 1, 0, 1, 1]) . "\n"; // Output: 1
echo maxSum([1, 2, -1, -2, 1, 0, -1]) . "\n"; // Output: 3
?> Explanation:
This approach efficiently maximizes the subarray sum by leveraging the properties of distinct non-negative elements and their contiguity after deletions, providing an optimal solution. |
Beta Was this translation helpful? Give feedback.
We need to find the maximum sum of a contiguous subarray after deleting any number of elements (without making the array empty) such that all elements in the subarray are unique. The solution leverages the observation that if the maximum element in the array is negative, the answer is simply that maximum element. Otherwise, the solution involves summing all distinct non-negative elements in the array, as these can always be arranged into a contiguous subarray with unique elements after appropriate deletions.
Approach