S - Max-Sum-Subarray
因为有图片 复制不全
You are given an array of integers.
You need to find the contiguous subarray of the maximum sum in . The subarray should not contain the number . Please find the maximum sum that is possible.
Note 1: The subarray can also be empty.
Note 2: The answer will fit in 32 bit-signed integer.
Input Format
The first line contains the integer N. The next line contains integers representing the numbers in the array.
Constraints
Output Format
Output a single line representing the maximum sum that can be obtained.
Sample Input
5
3 4 0 1 2
Sample Output
7
Explanation
The subarray with the maximum sum that doesn't contain a 0 is 3,4
Hence, the sum is .7
一开始简单的比较0与0之间的序列哪个大
后来定睛一看,原来Ai可以是负数! 哈哈 就说不能那么简单
那么就转换为一个DP问题了
对于位置i,dp[i]为这个点的最大序列和
那么dp[i]=dp[i-1]+arr[i] if dp[i-1]>=0
else dp[i] = arr[i]
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long arr[] = new long[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextLong();
}
long ans = 0;
for (int i = 0; i < arr.length; i++) {
if(arr[i]>0) break;
}
long dp[] = new long[n];
if(arr[0]==0) dp[0] = 0;
else dp[0] = arr[0];
for (int i = 1; i < arr.length; i++) {
if(arr[i]==0) dp[i]=0;
else if(dp[i-1]>0) {
dp[i] = dp[i-1]+arr[i];
}else {
dp[i] = arr[i];
}
}
for (int i = 0; i < dp.length; i++) {
if(dp[i]>ans) ans=dp[i];
}
System.out.println(ans);
}
}