Lintcode1833 · pen box go

/**
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
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值