1749. Maximum Absolute Sum of Any Subarray #1363
-
Topics: You are given an integer array Return the maximum absolute sum of any (possibly empty) subarray of Note that
Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the maximum absolute sum of any subarray (which can be empty) in a given array of integers. The key insight is that the maximum absolute sum can come from either the maximum subarray sum or the minimum subarray sum, considering their absolute values. Approach
Let's implement this solution in PHP: 1749. Maximum Absolute Sum of Any Subarray <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function maxAbsoluteSum($nums) {
$n = count($nums);
if ($n == 0) return 0;
// Compute maximum subarray sum (non-empty)
$current_max = $nums[0];
$global_max = $current_max;
for ($i = 1; $i < $n; $i++) {
$current_max = max($nums[$i], $current_max + $nums[$i]);
$global_max = max($global_max, $current_max);
}
$max_sum = max($global_max, 0);
// Compute minimum subarray sum (non-empty)
$current_min = $nums[0];
$global_min = $current_min;
for ($i = 1; $i < $n; $i++) {
$current_min = min($nums[$i], $current_min + $nums[$i]);
$global_min = min($global_min, $current_min);
}
$min_sum = min($global_min, 0);
return max(abs($max_sum), abs($min_sum));
}
// Test cases
$nums1 = [1,-3,2,3,-4];
echo maxAbsoluteSum($nums1) . "\n"; // Output: 5
$nums2 = [2,-5,1,-4,3,-2];
echo maxAbsoluteSum($nums2) . "\n"; // Output: 8
?> Explanation:
This approach efficiently computes the required values in linear time, making it suitable for large input arrays. |
Beta Was this translation helpful? Give feedback.
We need to find the maximum absolute sum of any subarray (which can be empty) in a given array of integers. The key insight is that the maximum absolute sum can come from either the maximum subarray sum or the minimum subarray sum, considering their absolute values.
Approach