一、求所有子数组的和的最大值

public static void main(String[] args) {
        int[] a = { 1, -2, 3, 10, -4, 7, 2, -5 };
        FindMaxSubAry(a);
    }

    public static void FindMaxSubAry(int[] arr) {
        int maxStartIndex = 0;// 最大数组开始坐标
        int maxEndIndex = 0; // 最大数组结束坐标
        int max = 0; // 最大数组的和
        int tempSum = 0;
        for (int i = 0; i < arr.length; i++) {
            tempSum += arr[i];
            if (tempSum <= 0) {
                tempSum = 0;
                max = 0;
                maxStartIndex = i + 1;
            }
            if (tempSum > max) {
                max = tempSum;
                maxEndIndex = i;
            }
        }
        System.out.println(" sum:" + max);
        print(arr, maxStartIndex, maxEndIndex);
    }

    public static void print(int[] arr, int startIndex, int endIndex) {
        for (int i = startIndex; i <= endIndex; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }
View Code

相关文章:

  • 2022-02-12
  • 2021-08-30
  • 2021-10-28
  • 2021-08-09
  • 2022-12-23
  • 2021-05-09
  • 2022-01-08
  • 2022-12-23
猜你喜欢
  • 2022-02-22
  • 2021-10-28
  • 2022-01-08
  • 2021-07-20
  • 2022-02-13
  • 2021-06-17
  • 2021-06-04
相关资源
相似解决方案