题解 | #环形数组的连续子数组最大和#
环形数组的连续子数组最大和
http://www.nowcoder.com/practice/53a9f1ba687440cc9c641c2b042a59d7
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = sc.nextInt();
}
int[] dpMax = new int[n];
int[] dpMin = new int[n];
int sum = nums[0];
int maxVal = nums[0];
int minVal = nums[0];
dpMax[0] = nums[0];
dpMin[0] = nums[0];
for (int i = 1; i < n; i++) {
dpMax[i] = Math.max(dpMax[i - 1] + nums[i], nums[i]);
maxVal = Math.max(maxVal, dpMax[i]);
dpMin[i] = Math.min(dpMin[i - 1] + nums[i], nums[i]);
minVal = Math.min(minVal, dpMin[i]);
sum += nums[i];
}
if (maxVal > 0) System.out.println(Math.max(maxVal, sum - minVal));
else System.out.println(maxVal);
}
}