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;
    }
};
相关推荐
油泼辣子多加2 分钟前
【华为OD机考】华为OD笔试真题解析(20)--投篮大赛
数据结构·算法·华为od
CodeJourney.1 小时前
Deepseek助力思维导图与流程图制作:高效出图新选择
数据库·人工智能·算法
Liudef061 小时前
Stable Diffusion模型高清算法模型类详解
人工智能·算法·ai作画·stable diffusion
一只_程序媛2 小时前
【leetcode hot 100 54】螺旋矩阵
windows·leetcode·矩阵
柠石榴2 小时前
【练习】【二叉树】力扣热题100 102. 二叉树的层序遍历
c++·算法·leetcode·二叉树
邴越2 小时前
Leetcode 112: 路径总和
算法·leetcode·职场和发展
2301_801037732 小时前
力扣-字符串
算法·leetcode·职场和发展
冠位观测者2 小时前
【Leetcode 每日一题】1328. 破坏回文串
数据结构·算法·leetcode
一只_程序媛2 小时前
【leetcode hot 100 53】最大子数组和
算法·leetcode·职场和发展
邴越2 小时前
Leetcode 57: 插入区间
算法·leetcode·职场和发展