3381. Maximum Subarray Sum With Length Divisible by K #2470
-
|
Topics: You are given an array of integers Return the maximum sum of a subarray1 of Example 1:
Example 2:
Example 3:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We have two prefix sums at indices
Approach:
Let's implement this solution in PHP: 3381. Maximum Subarray Sum With Length Divisible by K <?php
/**
* @param Integer[] $nums
* @param Integer $k
* @return Integer
*/
function maxSubarraySum($nums, $k) {
$ans = PHP_INT_MIN;
$prefix = 0;
// minPrefix[i % k] := the minimum prefix sum at position i % k
$minPrefix = array_fill(0, $k, PHP_INT_MAX / 2);
$minPrefix[($k - 1) % $k] = 0;
for ($i = 0; $i < count($nums); $i++) {
$prefix += $nums[$i];
$mod = $i % $k;
$ans = max($ans, $prefix - $minPrefix[$mod]);
$minPrefix[$mod] = min($minPrefix[$mod], $prefix);
}
return $ans;
}
// Test cases
echo maxSubarraySum([1,2], 1) . "\n"; // Output: 3
echo maxSubarraySum([-1,-2,-3,-4,-5], 4) . "\n"; // Output: -10
echo maxSubarraySum([-5,1,2,-3,4], 2) . "\n"; // Output: 4
?>Explanation:
Complexity
|
Beta Was this translation helpful? Give feedback.
We have two prefix sums at indices
iandjwhere(i % k) == (j % k), then the subarray fromi+1tojhas length(j - i)which is divisible byk. This is because:i % k == j % kimplies(j - i) % k == 0Approach:
Let's implement this solution in PHP: 3…