Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
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.
Seen this question in a real interview before? No
Thanks for your feedback.
Difficulty:Easy
Total Accepted:345.9K
Total Submissions:845.3K
Contributor:LeetCode
Subscribe to see which companies asked this question.
Related Topics
ArrayDivide and ConquerDynamic Programming
Similar Questions
Best Time to Buy and Sell StockMaximum Product SubarrayDegree of an Array
Java
1
class Solution {
2
3
public int maxSubArray(int[] nums) {
4
int sum = nums[0];
5
int result = nums[0];
6
for (int i = 1; i < nums.length; i++) {
7
if (sum < 0) {
8
if (nums[i] > sum) {
9
sum = nums[i];
10
result = Math.max(result, nums[i]);
11
}
12
} else {
13
result = Math.max(result, sum + nums[i]);
14
sum += nums[i];
15
16
}
17
}
18
return result;
19
20
}
21
}