5874. 分割数组的最多方案数

思路

分割数组的最多方案数

  • 考查点:前缀和+哈希表
  • 看到有连续的子数组和,很明显在提示用前缀和,分析出要尽快获取前后缀匹配的数量,可以用哈希表。比较难处理的就是题目可以改变数组中某个数组,此时只影响前缀和后面的结果,因此我们可以将要查的值分为两段。
    • 当前修改元素之前的数
    • 当前修改元素之后的数
  • 更新数组后,目标值也改变了,我们可以考虑在修改元素之前求目标值,更新元素之后求修改后的目标值,两者之和即是结果。
  • 注意点:
    • 结果可能会超过int,记得使用long long
  • 62场双周赛,这是我最接近AK的一次,可惜了,还要继续加油鸭!

代码

class Solution {
    
    
public:
    using LL = long long;
    int waysToPartition(vector<int>& nums, int k) {
    
    
        // 前后缀和
        int n = nums.size();
        vector<LL> sum(n+1);
        unordered_map<LL, int> oldR, newL;
        
        for(int i = 1; i <= n; i++){
    
    
            sum[i] = sum[i-1] + nums[i-1];
            if(i > 1) oldR[sum[i-1]]++;
        }
        LL tot = sum[n];
        int res = 0;
        // 不改变
        if(tot % 2 == 0){
    
    
            res = oldR[tot/2];
        }
        // cout<<res<<endl;
        // 改变一个位置
        for(int i = 1; i <= n; i++){
    
    
            int d = k - nums[i-1];
            if((tot + d) % 2 == 0){
    
    
                res = max(res, newL[(tot+d)/2] + oldR[(tot-d)/2]);
            }
            newL[sum[i]]++;
            oldR[sum[i]]--;
        }
        
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/SYaoJun/article/details/120591526