最大子数组和

今天上课的课堂练习其实是一道力扣里的算法题

 

 

 我写的代码是:

package example;

import java.util.Scanner;

public class ceshi_sum_max {
    public static void main(String[] args) {

        Scanner cin = new Scanner(System.in);

        int[] list = new int[1000000];
        int n = cin.nextInt();
        for (int i = 0; i < n; i++) {
            list[i] = cin.nextInt();
        }

        int sum=0,max=list[0];
        for(int i=0;i<n;i++){
            sum+=list[i];
            if(sum>max){
                max=sum;
            }else if(sum<max){
                sum=0;
            }
        }

        System.out.println(max);
    }


}

最厉害的算法是:

public class Solution {

    public int maxSubArray(int[] nums) {
        int pre = 0;
        int res = nums[0];
        for (int num : nums) {
            pre = Math.max(pre + num, num);
            res = Math.max(res, pre);
        }
        return res;
    }
}
posted @ 2023-03-06 19:51  一统天下。  阅读(7)  评论(0编辑  收藏  举报