1. 程式人生 > >數字陣列連續數相加求最大和

數字陣列連續數相加求最大和

public static void main(String[] args) {
    // 定義資料來源
    int[] source = {-1, 2, -2, 30, -1, 6, -8, 6};
    // 陣列長度
    List<String> xx = new ArrayList(8);
    int arrLen = source.length;
    int start = 0;
    int end = 1;
    int total = source[0] + source[1];
    for (int i = 0; i < arrLen; i++) {
        int 
sum = source[i]; for (int j = i + 1; j < arrLen; j++) { sum += source[j]; if (sum > total) { xx.clear(); start = i; end = j; total = sum; xx.add("start=" + i + " end=" +j); }else if
(sum == total){ xx.add("start=" + i + " end=" +j); } } } System.out.println(start); System.out.println(end); System.out.println(total); System.out.print(xx); }