欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

箭指Offer之连续子数组求最大值

程序员文章站 2022-04-11 19:00:49
...

茶语: 求职实习生才发现,原来会考核手写编程题,虽然比较简单,可还是栽了,算法题刷起来

题目

箭指Offer之连续子数组求最大值

示例

箭指Offer之连续子数组求最大值

思路
  • 读取个数,遍历生成数组
  • 数组遍历,last保留历史最大值(max不能作为保存最大值,遇到负数max会减少)
代码实现
import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int str = Integer.parseInt(sc.nextLine());
        if(str<=1){
            System.out.println(sc.nextLine());
        }else{
            int[] nums = new int[str];
            for(int i=0;i<str;i++){
                nums[i]=sc.nextInt();

            }
            int max = nums[0];int last = nums[0];
            for(int j=1;j<nums.length;j++){
               max = Math.max(nums[j],max+nums[j]);
                last = Math.max(last,max);
            }
            System.out.println(last);

        }
    }


}