最大子数组和

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

 

 

 我写的代码是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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);
    }
 
 
}

最厉害的算法是:

1
2
3
4
5
6
7
8
9
10
11
12
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 @   一统天下。  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示