P1115 Maximum sub-segment sum (one-dimensional prefix and Java)

P1115 Maximum sub-segment sum

Topic link: https://www.luogu.com.cn/problem/P1115

Title description

Given a sequence a of length n, select a continuous and non-empty segment to maximize the sum.

Input format

The first line is an integer, indicating the length of the sequence n.

The second line has n integers, and the i-th integer represents the i-th number ai of the sequence.

Output format

Output an integer on a line to indicate the answer.

Sample input and output

Input #1
7
2 -4 3 -1 2 -4 3
Output #1
4
Explanation/Prompt
Example 1 Explanation
Select [3, 5] subsection {3,−1,2}, and the sum is 4.

Data scale and agreement
For 40% of the data, ensure that n≤ 2×10^3.
For 100% data, ensure that 1≤n≤2×10^5, −10^4 ≤ai ≤10^4.

Problem-solving ideas:

One-dimensional prefix sum: f[i] = max(w[i], w[i] + f[i-1])

code show as below:

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);
	}
}

Guess you like

Origin blog.csdn.net/weixin_45894701/article/details/114867435