Maximum Subarray
2019-02-21 本文已影响0人
小明今晚加班
题目描述:
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.
分析从一个数组中,找到某几个连续的值之和最大,并返回。(如果需要记录是哪个连续的数字串的话,只需要在if条件中记录下标即可)
我的Code如下:
public int maxSubArray(int[] nums) {
int sum = nums[0];
for(int i=0; i<nums.length; i++){
int subSum=0;
for(int j=i; j<nums.length; j++){
subSum+=nums[j];
if(subSum > sum){
sum = subSum;
}
}
}
return sum;
}