Tutorialspoint
Problem
Solution
Submissions

Find The Maximum Sum Subarray

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 8

Write a C# program to implement the MaximumSumSubarray(int[] arr, int k) function to find the maximum sum subarray of size K in a given array of integers. The algorithm should efficiently find the contiguous subarray of size K that has the maximum sum.

Example 1
  • Input: arr = [2, 1, 5, 1, 3, 2], K = 3
  • Output: 9
  • Explanation:
    • Step 1: Use a sliding window of size K = 3 to efficiently compute sums.
      • Window [2, 1, 5] has sum 8
      • Window [1, 5, 1] has sum 7
      • Window [5, 1, 3] has sum 9
      • Window [1, 3, 2] has sum 6
    • Step 2: Track the maximum sum encountered (9 from window [5, 1, 3]).
    • Step 3: Return the maximum sum, which is 9.
Example 2
  • Input: arr = [1, 4, 2, 10, 23, 3, 1, 0, 20], K = 4
  • Output: 39
  • Explanation:
    • Step 1: Use a sliding window of size K = 4 to efficiently compute sums.
      • Window [1, 4, 2, 10] has sum 17
      • Window [4, 2, 10, 23] has sum 39
      • Window [2, 10, 23, 3] has sum 38
      • Window [10, 23, 3, 1] has sum 37
      • Window [23, 3, 1, 0] has sum 27
      • Window [3, 1, 0, 20] has sum 24
    • Step 2: Track the maximum sum encountered (39 from window [4, 2, 10, 23]).
    • Step 3: Return the maximum sum, which is 39.
Constraints
  • 1 ≤ arr.length ≤ 10^5
  • -10^4 ≤ arr[i] ≤ 10^4
  • 1 ≤ K ≤ arr.length
  • Time Complexity: O(n) where n is the length of the input array
  • Space Complexity: O(1) using constant extra space
ArraysKPMGSwiggy
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 the sliding window technique to avoid recalculation
  • Calculate the sum of first K elements
  • Slide the window by one element and keep updating the maximum sum
  • Avoid the brute force approach of recalculating the sum for each window

Steps to solve by this approach:

 Step 1: Check if the array length is less than K. If so, return an error.

 Step 2: Calculate the sum of the first K elements in the array.
 Step 3: Initialize the maximum sum as the sum of the first window.
 Step 4: Slide the window by adding the next element and removing the first element of the previous window.
 Step 5: Update the maximum sum if the current window sum is greater.
 Step 6: Repeat steps 4-5 until the end of the array.
 Step 7: Return the maximum sum found.

Submitted Code :