很蠢但能通过的方法:k >= 3时,算三次res。如果res2 - res2 == res3 - res2,说明为等差数列。如果res2 - res2 != res3 - res2,说明循环多次的结果都是一样的。
class Solution { public: int kConcatenationMaxSum(vector<int>& arr, int k) { const int MOD = 1'000'000'007; int size = arr.size(); if(size == 1){ if(arr[0] > 0) return (arr[0] * k) % MOD; else return 0; } vector<int> dp(size); dp[0] = arr[0]; int res = arr[0]; for(int i = 1;i < size;++i){ dp[i] = max(dp[i-1] + arr[i],arr[i]); res = max(res,dp[i]); } if(res < 0) return 0; if(k == 1) return res % MOD; int t1Res = res; for(int i = 0;i < size;++i){ if(i == 0){ dp[0] = max(dp[size-1] + arr[0],arr[0]); res = max(res,dp[0]);continue; } dp[i] = max(dp[i-1] + arr[i],arr[i]); res = max(res,dp[i]); } if(k == 2) return res % MOD; int t2Res = res; for(int i = 0;i < size;++i){ if(i == 0){ dp[0] = max(dp[size-1] + arr[0],arr[0]); res = max(res,dp[0]);continue; } dp[i] = max(dp[i-1] + arr[i],arr[i]); res = max(res,dp[i]); } if(k == 3) return res % MOD; if(t2Res - t1Res != res - t2Res) return res; return (t1Res + (long)(k-1)*(t2Res-t1Res)) % MOD; } };
标签:串联,arr,1191,res,int,max,leetcode,dp,size From: https://www.cnblogs.com/uacs2024/p/18642538