LintCode 406: Minimum Size Subarray Sum (同向双指针经典题!!!)

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

Example
Given the array [2,3,1,2,4,3] and s = 7, the subarray [4,3] has the minimal length under the problem constraint.

Challenge
If you have figured out the O(nlog n) solution, try coding another solution of which the time complexity is O(n).

思路:同向双指针
注意:

  1. 凡是题目提到子串,子数组之类的,多考虑双指针(可能同向,也可能反向);
  2. 子串之类的题目有单调性,即超过某个就都满足
    左边不行右边行 - 最短子串, 如此题
    左边行右边不行 - 最长子串, 如Longest Substring Without Repeating Characters ???
  3. 同向双指针模板:右指针用for loop, 左指针嵌在for loop里面用while loop。满足条件时更新最大/小值,移动左指针并更新sum。
  4. 注意while loop的条件是 sum>=s,即==s的情况也必须考虑。LintCode 386的while loop也是一样。

代码如下:

class Solution {
public:
    /**
     * @param nums: an array of integers
     * @param s: An integer
     * @return: an integer representing the minimum size of subarray
     */
    int minimumSize(vector<int> &nums, int s) {
        int len = nums.size();
        if (len == 0) return -1;
        
        int left = 0;
        int minLen = INT_MAX;
        int sum = 0;
        
        for (int right = 0; right < len; ++right) {
            sum += nums[right];
            while (sum >= s) {  //注意这里是>=s,即==s的情况也考虑
                minLen = min(minLen, right - left + 1);
                sum -= nums[left];
                left++;
            }
        }
    
        return (minLen == INT_MAX) ? -1 : minLen;
    }
};

二刷:

class Solution {
public:
    /**
     * @param nums: an array of integers
     * @param s: An integer
     * @return: an integer representing the minimum size of subarray
     */
    int minimumSize(vector<int> &nums, int s) {
        int n = nums.size();
        int left = 0, right = 0;
        int sum = 0, res = INT_MAX;
        while (right < n) {
            sum += nums[right];
            right++;
            while (sum >= s) {
                res = min(res, right - left);
                sum -= nums[left];
                left++;
            }
        }
        return res == INT_MAX ? -1 : res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
This problem can be solved using binary search. We can try to find the minimum possible maximum sum in a subarray by binary searching over the range of possible values. The upper bound of this range is the sum of all elements in the array, since each subarray must have at least one element. The lower bound of this range is the maximum element in the array, since each subarray must have at least one element and the maximum element must be in its own subarray. For each guess of the maximum sum, we can try to divide the array into subarrays such that no subarray has a sum greater than the guess. This can be done by iterating through the array and greedily assigning each element to the current subarray until the sum of the subarray is greater than the guess. Then, we start a new subarray with the current element. If we can divide the array into k subarrays with a maximum sum no greater than our guess, we can try a smaller guess. If we cannot divide the array into k subarrays with a maximum sum no greater than our guess, we need to try a larger guess. Here's some sample code in Python: ``` n, k = map(int, input().split()) arr = list(map(int, input().split())) low = max(arr) high = sum(arr) while low < high: mid = (low + high) // 2 count = 1 total = 0 for x in arr: if total + x > mid: count += 1 total = x else: total += x if count > k: low = mid + 1 else: high = mid print(low) ``` This code reads in the input and initializes the range of possible values for the maximum sum in a subarray. Then, it performs binary search to find the minimum possible maximum sum. For each guess of the maximum sum, it tries to divide the array into k subarrays such that no subarray has a sum greater than the guess. If it can do this, it tries a smaller guess. If not, it tries a larger guess. Finally, it prints out the minimum possible maximum sum.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值