數字數組連續數相加求最大和

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);
}
相關文章
相關標籤/搜索