LC053 - Maximum Subarray
Last updated
Last updated
Given an integer array nums
, find the subarray with the largest sum, and return its sum.
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The subarray [4,-1,2,1] has the largest sum 6.
Calculate the sum of every possible subarray, which is cubic since we have n operations iterating the start index, n times for the end index, and n operations to calculate the sum itself from the available indices.
Subarrays are supersets of smaller subarrays, so we don't have to calculate the results from scratch, reducing the time complexity to .
Consider the current accumulated sum, if it is positive, then include it in the result, if it is negative, just start the subarray in the following. The time complexity of this solution is .