Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4]
,
the contiguous subarray [4,-1,2,1]
has the largest sum = 6
.
使用subarray的方式进行处理
java
class Solution {
public int maxSubArray(int[] nums) {
if (nums == null || nums.length == 0) {
return -1;
}
int sum = 0;
int max = Integer.MIN_VALUE;
int min = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
max = Math.max(max, sum - min);
min = Math.min(sum, min);
}
return max;
}
}
python
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums == None or len(nums) == 0:
return -1
value, maximum, minmum = 0, float('-inf'), 0
for element in nums:
value += element
maximum = max(maximum, value - minmum)
minmum = min(value, minmum)
return maximum