前缀
import java.util.Scanner; import java.util.stream.Stream; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[] v = sc.nextLine().split(","); int[]p = new int[v.length+1]; p[0] = Integer.parseInt(v[0]); if(v.length==1) { System.out.println(p[0]>0?p[0]:0); return; } for(int i=1;i<v.length;++i) { p[i] = p[i-1]+Integer.parseInt(v[i]); } int max = 0; for(int i=1;i<v.length;++i) { "" 暴力解决 时间复杂度为 O(N^2) "" } System.out.println(max); } public static int max(Integer... a) { return Stream.of(a).max(Integer::compare).get(); } }
方法二:
动态规划
import java.util.Arrays; import java.util.Scanner; import java.util.stream.Stream; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[] v = sc.nextLine().split(","); int[]dp = new int[v.length+1]; dp[0] = Integer.parseInt(v[0]); if(v.length==1) { System.out.println(dp[0]>0?dp[0]:0); return; } for(int i=1; i<v.length;++i) { int cur = Integer.parseInt(v[i]); dp[i] = max( dp[i-1]+cur, cur); } System.out.println(max(dp)); } public static int max(Integer... a) { return Stream.of(a).max(Integer::compare).get(); } public static int max(int[] a) { return Arrays.stream(a).max().getAsInt(); } }