Maximum Subarray
Last updated
Last updated
Given an integer array nums
, find the
subarraywith the largest sum, and return its sum.
Example 1:
Example 2:
Example 3:
Constraints:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
Follow up: If you have figured out the O(n)
solution, try coding another solution using the divide and conquer approach, which is more subtle.
You can solve this problem using the Kadane's algorithm, which is an efficient dynamic programming approach. Here's the JavaScript implementation:
This implementation iterates through the array once, maintaining two variables: maxSum
to keep track of the maximum sum found so far, and currentSum
to keep track of the sum of the current subarray. At each iteration, it updates currentSum
to be the maximum of the current element and the sum of the current element plus the previous sum. It also updates maxSum
to be the maximum of maxSum
and currentSum
. Finally, it returns maxSum
, which represents the largest sum of any subarray within the given array.