LintCode 1833: pen box (双指针好题)

1833. pen box

Given you an array boxes and a target. Boxes[i] means that there are boxes[i] pens in the ith box. Subarray [i, j] is valid if sum(boxes[i] + boxes[i+1] + ... + boxes[j]) == target. Please find two not overlapped valid subarrays and let the total length of the two subarrays minimum. Return the minimum length. If you can not find such two subarrays, return -1.

boxes.length <= 10 ^ 610​6​​ and boxes[i] > 0

Example

Example 1

Input:
boxes = [1,2,2,1,1,1],
target = 3

Output: 4

解法1:这题我感觉O(n)的解法并不容易。参考网上的答案。

思路是presums加上同向双指针。为啥是同向双指针呢?因为presums是递增数组,那么,这题就可以看成是两数之差等于定值那题(Lintcode 610)的变种了。
我们采用挡板法,每个挡板i处求出left_min[i]和right_min[i]。然后求其和的最小值即可。
left_min[]数组的求法和两数之差等于定值那题一样,但是我们不光要求两数之差等于target,而且还要求这两个数之间的间隔最小,所以还要用到 left_min[right] = min(left_min[right - 1], left_min[right])。
求right_min[]数组也一样。
如果输入是[1,1,1,2,1,1,1,1,1,1,2,1,1,1],target=2,那么结果应该等于2。因为第1个2和第2个2都等于target, 它们的长度都为1,加起来是2。

class Solution {
public:
    /**
     * @param boxes: number of pens for each box
     * @param target: the target number
     * @return: the minimum boxes
     */
    int minimumBoxes(vector<int> &boxes, int target) {
        int n = boxes.size();
        if (n == 0) return 0;
        vector<int> presums(n + 1, 0);
        int res = INT_MAX / 3;
        
        for (int i = 1; i <= n; ++i) {
            presums[i] = presums[i - 1] + boxes[i - 1];
        }

        vector<int> left_min(n + 1, INT_MAX / 3); //left_min[i] is the min length of boxes[0..i] (left->right)
        int left = 0, right = 1;
        for (right = 1; right <= n; ++right) {
            while (left < right && presums[right] - presums[left] > target) {
                left++;
            }
            if (presums[right] - presums[left] == target) {
                left_min[right] = right - left;
            }
            left_min[right] = min(left_min[right - 1], left_min[right]);
        }
        

        vector<int> right_min(n + 1, INT_MAX / 3); //right_min[i] is the min length of boxes[i..n-1] (right->left)
        right = n;
        for (left = n - 1; left > 0; --left) {
            while(left < right && presums[right] - presums[left] > target) {
                right--;
            }
            if (presums[right] - presums[left] == target) {
                right_min[left] = right - left;
                res = min(res, left_min[left] + right_min[left]);
            }
            right_min[left] = min(right_min[left + 1], right_min[left]);
        }
        
        return res > n ? -1 : res;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值