关于各种子数组的和sum小于或者等于k这一类问题的总结

本文总结了在数组中寻找子数组和小于或等于k的各种情况。针对全正数数组,推荐使用双指针算法;当包含负数时,利用前缀和与单调队列。在遇到时间复杂度过高的问题时,可以采用hash表或单调队列进行优化。具体应用包括Minimum Size Subarray Sum、Maximum Subarray、Subarray Sum Equals K以及Shortest Subarray with Sum at Least K等题目。
摘要由CSDN通过智能技术生成

这种类型的情况可以分为两大类

1、当数组中全是正数的时候 用双指针算法
2、当数组中包括负数的时候用 前缀和 单调队列
**

如果在使用前缀和求解的过程中 时间复杂度超时的情况

优化的方法主要有1、hash表 2、单调队列

209. Minimum Size Subarray Sum
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn’t one, return 0 instead.

Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
思路 数组里全是正整数 使用双指针算法找到最小长度 因为都是整数可以让sum一直是单调递增
指针,移动指针可以指定什么时候该从队头弹出什么时候从队尾弹出类似单调队列的思想

class Solution {
public:
    int minSubArrayLen(int s, vector<int>& nums) {
      if(nums.size()==0) return 0;
      int n=nums.size();
      int len=1e10;
      int sum=0;
      for(int i=0,j=0;j<n;j++)
      {
          sum+=nums[j];
          if(sum>=s)
          {
             while((sum-nums[i])>=s) 
             {
                 sum-=nums[i];
                 i++;
             }
             len=min(len,j-i+1);
          } 
      }
      if(sum<s) return 0;
      return len;
    }
};

53. Maximum Subarra
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
思路:枚举每一位以i结尾的字数组如果前面的和小于当前数字就那么就结算当前数字作为最大字数组

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        if(nums.size()==0) return 0;
        int n=nums.size();
        vector<int> dp(n,0);
        dp[0]=nums[0];
        int maxval=nums[0];
        for(int i=1;i<n;i++)
        {
    
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值