LeetCode 1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target(动态规划)
题意:在一个数组中,找到最多的不相交的子序列,每个子序列的和等于target。
题解:动态规划 dp[i]表示从0到i的子数组的答案。维护前缀数组sums[],我们维护一个记录前缀和的map,map[x]表示前缀和是x距离当前i最近的下标。
那么状态转移方程就是dp[i] = max(dp[i-1], dp[map[sums[i]-target]]+1)
class Solution {
public:
int dp[100005];
int sum[100005];
map<int, int> m;
int maxNonOverlapping(vector<int>& nums, int target) {
sum[0] = nums[0];
dp[0] = 0;
if (nums[0] == target)
dp[0] = 1;
m[0] = -1;
m[nums[0]] = 0;
for (int i = 1; i < nums.size(); i++)
{
sum[i] = nums[i] + sum[i - 1];
int left = sum[i] - target;
if (m.find(left) == m.end())
{
dp[i] = dp[i - 1];
}
else
{
int pos = m[left];
dp[i] = max(dp[i - 1], (pos == -1 ? 0 : dp[pos]) + 1);
}
m[sum[i]] = i;
}
return dp[nums.size() - 1];
}
};