689. Maximum Sum of 3 Non-Overlapping Subarrays #1013
-
Topics: Given an integer array Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one. Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We will use a dynamic programming approach. The idea is to break down the problem into smaller subproblems, leveraging the overlap of subarrays to efficiently calculate the maximum sum of three non-overlapping subarrays of length Approach:
Let's implement this solution in PHP: 689. Maximum Sum of 3 Non-Overlapping Subarrays <?php
/**
* @param Integer[] $nums
* @param Integer $k
* @return Integer[]
*/
function maxSumOfThreeSubarrays($nums, $k) {
$n = count($nums);
// Step 1: Calculate all the subarray sums of length k
$sum = [];
$windowSum = 0;
for ($i = 0; $i < $k; $i++) {
$windowSum += $nums[$i];
}
$sum[0] = $windowSum;
for ($i = $k; $i < $n; $i++) {
$windowSum += $nums[$i] - $nums[$i - $k];
$sum[$i - $k + 1] = $windowSum;
}
// Step 2: Dynamic programming for left and right max sums
$left = [];
$right = [];
$leftMaxSum = 0;
for ($i = 0; $i < $n - $k + 1; $i++) {
if ($sum[$i] > $sum[$leftMaxSum]) {
$leftMaxSum = $i;
}
$left[$i] = $leftMaxSum;
}
$rightMaxSum = $n - $k;
for ($i = $n - $k; $i >= 0; $i--) {
if ($sum[$i] >= $sum[$rightMaxSum]) {
$rightMaxSum = $i;
}
$right[$i] = $rightMaxSum;
}
// Step 3: Find the best middle subarray and combine with left and right
$maxSum = 0;
$result = [];
for ($j = $k; $j <= $n - 2 * $k; $j++) {
$i = $left[$j - $k];
$l = $right[$j + $k];
$totalSum = $sum[$i] + $sum[$j] + $sum[$l];
if ($totalSum > $maxSum) {
$maxSum = $totalSum;
$result = [$i, $j, $l];
}
}
return $result;
}
// Test cases
print_r(maxSumOfThreeSubarrays([1,2,1,2,6,7,5,1], 2)); // [0, 3, 5]
print_r(maxSumOfThreeSubarrays([1,2,1,2,1,2,1,2,1], 2)); // [0, 2, 4]
?> Explanation:
Example:For the input: $nums = [1, 2, 1, 2, 6, 7, 5, 1];
$k = 2; The output will be: [0, 3, 5] This approach ensures that the time complexity remains efficient, with a time complexity of approximately O(n), where |
Beta Was this translation helpful? Give feedback.
We will use a dynamic programming approach. The idea is to break down the problem into smaller subproblems, leveraging the overlap of subarrays to efficiently calculate the maximum sum of three non-overlapping subarrays of length
k
.Approach:
Precompute the sums of subarrays of length
k
:First, we compute the sum of all subarrays of length
k
in the input arraynums
. This can be done efficiently in linear time by using a sliding window technique.Dynamic Programming (DP):
We create two auxiliary arrays,
left
andright
, to store the indices of the best subarrays found up to the current position. Theleft[i]
will store the index of the best subarray ending before indexi
, andright[i]
wi…