这种类型的情况可以分为两大类
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++)
{