LC053 - Maximum Subarray
Problem
Given an integer array nums
, find the subarray with the largest sum, and return its sum.
Example
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.
Solution
Naive
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.
Improved
Subarrays are supersets of smaller subarrays, so we don't have to calculate the results from scratch, reducing the time complexity to .
Greedy
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 .
Last updated