Tutorialspoint
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)
ArraysDynamic Programming PwCApple
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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.

Steps to solve by this approach:

 Step 1: Compute prefix sums for efficient subarray sum calculations
 Step 2: Define a dynamic programming table dp[i][j] to represent the maximum sum of j non-overlapping subarrays ending before position i
 Step 3: Initialize the table with the base case of j=1 (single subarray)
 Step 4: Fill the dp table for j=2 and j=3 by considering all valid positions
 Step 5: Track the starting indices that lead to optimal solutions
 Step 6: Find the position that gives the maximum sum for j=3
 Step 7: Reconstruct the solution by backtracking through the tracked indices

Submitted Code :