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 ^ 6106 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;
}
};