Tutorialspoint
Problem
Solution
Submissions

Maximum Subarray

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a JavaScript program to find the maximum sum of a contiguous subarray within a one-dimensional array of integers using Kadane's Algorithm. The subarray must contain at least one element.

Example 1
  • Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
  • Output: 6
  • Explanation:
    • We need to find the contiguous subarray with the maximum sum.
    • The subarray [4,-1,2,1] has the maximum sum of 6.
    • We calculate: 4 + (-1) + 2 + 1 = 6.
    • Therefore, the maximum subarray sum is 6.
Example 2
  • Input: nums = [5,4,-1,7,8]
  • Output: 23
  • Explanation:
    • We analyze all possible contiguous subarrays.
    • The entire array [5,4,-1,7,8] gives the maximum sum.
    • We calculate: 5 + 4 + (-1) + 7 + 8 = 23.
    • Therefore, the maximum subarray sum is 23.
Constraints
  • 1 ≤ nums.length ≤ 10^5
  • -10^4 ≤ nums[i] ≤ 10^4
  • The subarray must contain at least one element
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysAlgorithmsSnowflakeTutorix
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 Kadane's algorithm which maintains a running sum of the current subarray
  • Keep track of the maximum sum encountered so far
  • If the current sum becomes negative, reset it to 0 (start fresh)
  • Update the maximum sum whenever the current sum exceeds it
  • Iterate through the array only once to achieve O(n) time complexity

Steps to solve by this approach:

 Step 1: Initialize maxSoFar and maxEndingHere with the first element of the array.

 Step 2: Iterate through the array starting from the second element.
 Step 3: For each element, decide whether to extend the existing subarray or start a new one.
 Step 4: Update maxEndingHere to be the maximum of current element or sum of current element with previous subarray.
 Step 5: Update maxSoFar if maxEndingHere is greater than the current maximum.
 Step 6: Continue until all elements are processed.
 Step 7: Return maxSoFar as the result.

Submitted Code :