
Problem
Solution
Submissions
3 Non-Overlapping Subarrays
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C++ program to find three non-overlapping subarrays of length `k` that have the maximum sum and return the maximum sum and the starting indices of these subarrays.
Example 1
- Input: nums = [1,2,1,2,6,7,5,1], k = 2
- Output: [0,3,5]
- Explanation:
- Subarrays [1,2], [2,6], and [7,5] correspond to the starting indices [0,3,5].
- We get the maximum sum as 1+2 + 2+6 + 7+5 = 23.
Example 2
- Input: nums = [1,2,1,2,1,2,1,2,1], k = 2
- Output: [0,2,4]
- Explanation:
- Subarrays [1,2], [1,2], and [1,2] correspond to the starting indices [0,2,4].
- We get the maximum sum as 1+2 + 1+2 + 1+2 = 9.
- Other possible solutions are [0,2,6] and [0,4,6].
Constraints
- 1 ≤ nums.length ≤ 2 * 10^4
- 1 ≤ nums[i] < 2^16
- 1 ≤ k ≤ floor(nums.length / 3)
- Time Complexity: O(n) where n is the length of nums
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a sliding window to compute sums of all possible k-length subarrays.
- Use dynamic programming to track the maximum sum at each position.
- Work with prefix sums to optimize subarray sum calculations.
- Consider the problem as finding the best combination of first, second, and third subarrays.
- Use greedy approach with careful state tracking.