53. Maximum Subarray
Question:
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
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.
Example:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Input: nums = [1]
Output: 1
Input: nums = [0]
Output: 0
Input: nums = [-1]
Output: -1
Input: nums = [-2147483647]
Output: -2147483647
Source code
Version 1
Idea:
It is a brute force approach. Use 2 loop to calculate the sum for each elements.
1 | class Solution { |
Version 2
Idea:
This is an efficient method, use only one loop.
sum += nums[i]
means the cumulative sum.
sum = max(sum, nums[i])
means the maximum of sum between the cumulative sum or current index of value.
maxValue = max(maxValue, sum)
means recording the maximal value.
1 | class Solution { |