您的位置:首页 > 其它

求数组中最大连续子数组的和

2017-04-10 21:58 190 查看
package 最大连续子数组;

public class SubArray {
public static void main(String[] args) {
int[] arr = new int[] { 1, -2, 3, 10, -4, 7, 2, -5 };
int sum = getArraySum(arr);
System.out.println(sum);
}

public static int getArraySum(int[] arr) {
int max = 0;
if (arr == null || arr.length == 0) {
return 0;
}
int tmp = max;
for (int i = 0; i < arr.length; i++) {
tmp += arr[i];
if (tmp < 0) {
tmp = 0;
}
if (tmp > max) {
max = tmp;
}
}
if (tmp == 0) {
max = arr[0];
for (int j = 1; j < arr.length; j++) {
if (arr[j] > max) {
max = arr[j];
}
}
}

return max;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: