[LeetCode] 53. Maximum Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array
the contiguous subarray
[-2,1,-3,4,-1,2,1,-5,4]
,the contiguous subarray
[4,-1,2,1]
has the largest sum = 6
.
More practice:
Time complexity: O(n).
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
Thought process:
Iterate through the array and keep track of the maximum subarray that ends at current index. Update the global max based on current rolling max.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class Solution { public int maxSubArray(int[] nums) { int max = Integer.MIN_VALUE; int maxEndingHere = 0; for (int num : nums) { maxEndingHere = Math.max(maxEndingHere + num, num); max = Math.max(max, maxEndingHere); } return max; } } |
Time complexity: O(n).
Comments
Post a Comment