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;
    }
};
相关推荐
Miraitowa_cheems2 小时前
LeetCode算法日记 - Day 73: 最小路径和、地下城游戏
数据结构·算法·leetcode·职场和发展·深度优先·动态规划·推荐算法
野蛮人6号2 小时前
力扣热题100道之560和位K的子数组
数据结构·算法·leetcode
Swift社区3 小时前
LeetCode 400 - 第 N 位数字
算法·leetcode·职场和发展
fengfuyao9854 小时前
BCH码编译码仿真与误码率性能分析
算法
小白不想白a4 小时前
每日手撕算法--哈希映射/链表存储数求和
数据结构·算法
剪一朵云爱着4 小时前
力扣2080. 区间内查询数字的频率
算法·leetcode
落日漫游4 小时前
数据结构笔试核心考点
java·开发语言·算法
Dream it possible!5 小时前
LeetCode 面试经典 150_栈_有效的括号(52_20_C++_简单)(栈+哈希表)
c++·leetcode·面试··哈希表
workflower5 小时前
Fundamentals of Architectural Styles and patterns
开发语言·算法·django·bug·结对编程
仰泳的熊猫5 小时前
LeetCode:701. 二叉搜索树中的插入操作
数据结构·c++·算法·leetcode