#include <stdio.h>
#include <stdlib.h>
#include "string.h"
#include "math.h"
int maxSubarraySumCircular(int* nums, int numsSize) {
int n = numsSize;
int leftSum,pre,res;
int dp[n];
// 对坐标为 0 处的元素单独处理,避免考虑子数组为空的情况
dp[0] = nums[0];
// for (int i = 1; i < n; i++) {
// dp[i]=0;
// }
leftSum = nums[0];
pre = nums[0];
res = nums[0];
for (int i = 1; i < n; i++) {
pre = fmax(pre + nums[i], nums[i]);
res = fmax(res, pre);
leftSum += nums[i];
dp[i] = fmax(dp[i - 1], leftSum);
}
// 从右到左枚举后缀,固定后缀,选择最大前缀
int rightSum = 0;
for (int i = n - 1; i > 0; i--) {
rightSum += nums[i];
res = fmax(res, rightSum + dp[i - 1]);
}
printf("%d ",res);
// return res;
}
int main()
{
int nums[]={1,-2,3,-2};
maxSubarraySumCircular(nums,4);
return 0;
}
leetcode 918 环形子数组得最大和 动态规划
最新推荐文章于 2024-08-17 15:37:21 发布