/**
1833 · pen box
Algorithms
Medium
Accepted Rate
50%
DescriptionSolutionNotesDiscussLeaderboard
Description
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
Tags
https://blog.csdn.net/qq_46105170/article/details/111350999
https://www.lintcode.com/problem/1833/
*/
/**
* @param boxes: number of pens for each box
* @param target: the target number
* @return: the minimum boxes
*/
func minimumBoxes (boxes []int, target int) int {
// write your code here
var n int = len(boxes)
var lShort = make([]int, n)
var preSum = make([]int, n + 1)
for i := 0; i < n; i++ {
preSum[i + 1] = preSum[i] + boxes[i]
}
var j int = 0
for i := 1; i <= n; i++ {
for {
if preSum[i] - preSum[j] <= target {
break
}
j += 1
}
if preSum[i] - preSum[j] == target {
lShort[i - 1] = i - j
} else if i - 1 > 0 {
lShort[i - 1] = lShort[i - 2]
}
}
var res int = n + 1
j = n
for i := n - 1; i >= 1; i-- {
for {
if preSum[j] - preSum[i] <= target {
break
}
j -= 1
}
if preSum[j] - preSum[i] == target && lShort[i - 1] != 0 {
res = Min(res, lShort[i - 1] + j - i)
}
}
if res == n + 1 {
return -1
}
return res
}
func Min(a, b int) int {
if a < b {
return a
}
return b
}