题解 | 最大子段和

最大子段和

https://www.nowcoder.com/practice/f04519cd1d904f50b68f4229a126ab08

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] nums = new int[n];
        int index = 0;
        // 求解最大子段和问题的最优解:Kadane 算法
        // 优化了空间复杂度,思路还是动态规划的思路
        
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            nums[index] = in.nextInt();
            index++;
        }
        long maxSum = nums[0];
        long currentSum = nums[0]; // 当前子段和(以 i 结尾)
        for(int i = 1; i < n; i++){
            // 选择:要么延续前一段,要么从当前元素重新开始
            currentSum = Math.max(nums[i], currentSum + nums[i]);
            // 更新全局最大值
            maxSum = Math.max(maxSum, currentSum);
        }
        System.out.println(maxSum);
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务