Maximum Subarray
Array, Dynamic Programming
Given an integer array nums
, find the subarray with the largest sum, and return its sum. Here, array can contains duplicate or nagative numbers also.
Example 1:
Example 2:
Example 3:
Solutions
Calculates the maximum sum ending at each position and ensures that this sum is the maximum seen so far.
Approach – Brute Force Technique
This algorithm works by calculating the sum of every possible subarray in the input array and updating maxSum
whenever a larger sum is found.
Steps
Initialize: Set
maxSum
to the smallest possible integer. This variable will keep track of the maximum subarray sum we've encountered so far.Iterate through the array: For each element in the array (index
i
from 0 tonums.Length - 1
), calculate the sum of all subarrays starting at this position. This is done by another loop (indexj
fromi
tonums.Length - 1
) that adds the current element (nums[j]
) tosum
.Update
maxSum
: Ifsum
is greater thanmaxSum
, updatemaxSum
with the value ofsum
. This step keeps track of the maximum sum of any subarray seen so far.Return the result: After going through all the elements of the array and all possible subarrays, return
maxSum
which now contains the maximum sum of a subarray in the array.
Complexity
Time Complexity: O(n^2)
Auxiliary Space: O(1)
Approach – Dynamic Programming Technique
It calculates the maximum sum ending at each position and ensures that this sum is the maximum seen so far. If the sum becomes less than the current element, it means the sum of the previous subarray is negative and thus not worth keeping, so it starts a new subarray from the current position.
Steps
Initialize: Set
maxCurrent
andmaxGlobal
to the first element of the array. These variables will keep track of the maximum subarray sum we've encountered so far (maxGlobal
) and the maximum sum ending at the current position (maxCurrent
).Iterate through the array: For each element from the second to the last (index
i
from 1 tonums.Length - 1
), updatemaxCurrent
to be the maximum of the current element (nums[i]
) and the sum of the current element and the previousmaxCurrent
(maxCurrent + nums[i]
). This step essentially says, "consider the current element as the start of a new subarray or include it in the sum of the existing subarray."Update
maxGlobal
: IfmaxCurrent
is greater thanmaxGlobal
, updatemaxGlobal
with the value ofmaxCurrent
. This step keeps track of the maximum sum of any subarray seen so far.Return the result: After going through all the elements of the array, return
maxGlobal
which now contains the maximum sum of a subarray in the array.
Complexity
Time Complexity: O(n)
Auxiliary Space: O(1)
Last updated