P1115 最大子段和(一维前缀和Java)

P1115 最大子段和

题目链接:https://www.luogu.com.cn/problem/P1115

题目描述

给出一个长度为 n 的序列 a,选出其中连续且非空的一段使得这段和最大。

输入格式

第一行是一个整数,表示序列的长度 n。

第二行有 n 个整数,第 i 个整数表示序列的第 i个数字 ai 。

输出格式

输出一行一个整数表示答案。

输入输出样例

输入 #1
7
2 -4 3 -1 2 -4 3
输出 #1
4
说明/提示
样例 1 解释
选取 [3, 5]子段{3,−1,2},其和为 4。

数据规模与约定
对于 40% 的数据,保证 n≤ 2×10^3 。
对于 100% 的数据,保证1≤n≤2×10^5, −10^4 ≤ai ≤10^4。

解题思路:

一维前缀和:f[i] = max(w[i], w[i] + f[i - 1])

代码如下:

import java.util.Scanner;

public class Main {
    
    
	public static void main(String[] args) {
    
    
		Scanner sc = new Scanner(System.in);
		long[] w = new long[200010];
		long[] f = new long[200010];
		int n = sc.nextInt();
		long ans = -100000010;
		for (int i = 1; i <= n; i++) {
    
    
			w[i] = sc.nextLong();
			f[i] = Math.max(w[i], w[i] + f[i - 1]);
			ans = Math.max(ans, f[i]);
		}
		System.out.println(ans);
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_45894701/article/details/114867435