题目:
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
思路:
返回由相邻数组相加得到的最大的和
class Solution {
public int maxSubArray(int[] nums) {
int sum = nums[0];
int max = sum;
if(nums.length == 1) return nums[0];
for (int i = 1;i < nums.length; i++) {
sum = Math.max(nums[i],sum+nums[i]);//如果和小于nums[i],则sum=nums[i]
max = Math.max(max, sum);
}
return max;
}
}