2020-02-18 20:57:58
一、Maximum Subarray
經典的動态規劃問題。
問題描述:
問題求解:public int maxSubArray(int[] nums) {
int res = nums[0];
int n = nums.length;
int[] dp = new int[n];
dp[0] = nums[0];
for (int i = 1; i < n; i++) {
if (dp[i - 1] < 0) dp[i] = nums[i];
else dp[i] = dp[i - 1] + nums[i];
res = Math.max(res, dp[i]);
}
return res;
}
二、Maximum Sum Circular Subarray
public int maxSubarraySumCircular(int[] A) {
int n = A.length;
int sum = 0;
for (int num : A) sum += num;
int max = A[0];
int[] dp = new int[n];
dp[0] = A[0];
for (int i = 1; i < n; i++) {
if (dp[i - 1] < 0) dp[i] = A[i];
else dp[i] = A[i] + dp[i - 1];
max = Math.max(max, dp[i]);
}
int min = A[0];
for (int i = 1; i < n; i++) {
if (dp[i - 1] > 0) dp[i] = A[i];
else dp[i] = A[i] + dp[i - 1];
min = Math.min(min, dp[i]);
}
return max > 0 ? Math.max(max, sum - min) : max;
}