题解 | #环形数组的连续子数组最大和#
环形数组的连续子数组最大和
https://www.nowcoder.com/practice/53a9f1ba687440cc9c641c2b042a59d7?tpId=230&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Foj
先找出和最小的连续子数组,将该子数组移动到数组末尾,然后求最大连续子数组和
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] nums = new int[n]; for (int i = 0; i < nums.length; i++) { nums[i] = in.nextInt(); } System.out.println(maxSum(nums)); } public static int maxSum(int[] nums) { int n, max, min, minIndex; n = nums.length; int[] dp = new int[n]; minIndex = 0; min = dp[0] = nums[0]; for (int i = 1; i < n; i++) { // dp[i] = Math.max(dp[i-1] + nums[i], nums[i]); // max = Math.max(max, dp[i]); dp[i] = Math.min(dp[i - 1] + nums[i], nums[i]); if (dp[i] < min) { min = dp[i]; minIndex = i; } } //System.out.println("dp1 = " + Arrays.toString(dp)); int[] nums2 = new int[nums.length]; // 借用一个辅助数组,对原数组做处理 for (int i = minIndex + 1; i < n; i++) { nums2[i - minIndex - 1] = nums[i]; } for (int i = 0; i < minIndex + 1; i++) { nums2[n - 1 - minIndex + i] = nums[i]; } max = dp[0] = nums2[0]; for (int i = 1; i < n; i++) { dp[i] = Math.max(dp[i - 1] + nums2[i], nums2[i]); max = Math.max(max, dp[i]); } return max; } }