Leetcode 1477. 找两个和为目标值且不重叠的子数组 前缀和+DP

原题链接: Leetcode 1477. 找两个和为目标值且不重叠的子数组


cpp 复制代码
class Solution {
public:
    int minSumOfLengths(vector<int>& arr, int target) {
        int n=arr.size();
        int sum=0;
        int maxn=INT_MAX;
        vector<int> dp(n,maxn);//dp[i]表示以索引i之前的满足要求的子数组的长度的最小值
        map<int,int> mp;//mp[num]=i,表示从0到i,前缀和为num
        mp[0]=-1;//初始时
        int res=maxn;
        for(int i=0;i<n;i++){
            sum+=arr[i];
            if(i>0) dp[i]=dp[i-1];
            if(mp.count(sum - target)){
                int cur_len=i-mp[sum-target];
                int left_index=mp[sum-target];
                if(left_index>=0 && dp[left_index]!=INT_MAX){
                    res=min(res,dp[left_index]+cur_len);
                }
                if(i==0) dp[i]=min(maxn,cur_len);
                else dp[i]=min(dp[i-1],cur_len);
            }
            mp[sum]=i;
        }
        if(res==maxn) return -1;
        return res;
    }
};
相关推荐
j7~3 小时前
【穷举、深搜与回溯算法】一棵决策树讲透全排列与子集
数据结构·c++·算法·leetcode·回溯·递归
傅科摆 _ py3 小时前
DP,贪心,堆和栈,二分力扣复习
开发语言·python·算法
Shaoshing4 小时前
LeetCode100 42.接雨水
java·算法·leetcode
域限奇点访客4 小时前
用AI生成问卷的网站怎么选?看题目录入结构、题型映射和生成后的校验
算法
文丑颜不良啊5 小时前
LeetCode1261~1280题目解析
java·leetcode
not coder5 小时前
一文讲通--从树到红黑树
数据结构·算法
octopus_c5 小时前
C++ 入门
开发语言·c++·算法
ZhengEnCi6 小时前
2026年10月30日AI早报:Gemini 4 Carbon登顶、DeepSeek融资1055亿、智元机器人上岗实测
人工智能·算法
强哥聊算力6 小时前
《算力江湖·Intel帝国往事》第三集:安迪·格鲁夫的铁血时代:Intel为什么能把对手逼到墙角?
运维·人工智能·科技·算法·ai·gpu算力
Shaoshing6 小时前
LeetCode100 11. 盛最多水的容器
算法·leetcode