面试题31:连续子数组的最大和

题目:输入一个整型数组,数组里有正数也有负数。数组中一个或连续的多个整数组成一个子数组。求所有子数组的和的最大值。要求时间复杂度为O(n)

解答:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package offer;
public class {
public int findGreatestSum(int[] arr){
int greatest = 0x80000000;
int cursum=0;
for(int i=0;i<arr.length;i++){
if(cursum<=0)
cursum=arr[i];
else
cursum+=arr[i];
if(greatest<cursum)
greatest=cursum;
}
return greatest;
}
public static void main(String[] args){
int[] arr={-1,-2,-3,-10,-4,-7,2,-5};
t31 test = new t31();
System.out.println(test.findGreatestSum(arr));
}
}