Java
连续子数组的最大和
http://www.nowcoder.com/questionTerminal/459bd355da1549fa8a49e350bf3df484
Java
- 解题思路:
- 1.双重循环,求以每个字符开始的子数组,(如1,2,3)==》1;1,2;1,2,3;...
- 2.不断更新最大值(max初始值为array[0],每求得一个子数组sum就比较一次)
- 3.用first,last,记录子数组下标(初始值为0;每一次更新max,就记录下当时的循环下标)
import java.util.ArrayList;
public class Solution {
public int FindGreatestSumOfSubArray(int[] array) { int max =array[0]; int sum = 0; int first = 0; int last = 0; int length = array.length; ArrayList<Integer> res =new ArrayList<>(); for (int i = 0;i<length;i++){ sum=array[i]; if (sum>max){ max=sum; first=i; } for (int j = i+1;j<length;j++){ sum+=array[j]; if (sum>max){ max=sum; first = i; last = j ; } } } for (int i = first;i<=last;i++){ res.add(array[i]); } return max; }
}