![c45dfd4de70cb6c73f73dc3b4fc000d5.png](https://img-blog.csdnimg.cn/img_convert/c45dfd4de70cb6c73f73dc3b4fc000d5.png)
问题描述
给一个整数数组和整数K,求各个子数组求和的最大值,且最大值小于K。
栗子
Input: [1, 1, 4, 4], k = 3Output: 2Explanation: 子数组[1, 1],求和为2,小于3并且最大。Input: [1, 1, 4, 4], k = 6Output: 5Explanation: 子数组[1, 4],求和为5,小于6并且最大。
思路
如果用暴力方法,那就是遍历所有子数组,并且求和,至少要O(N*N)的时间。
首先要注意的是,子数组(, ]求和,可以理解为子数组[0, ]的和[]减去子数组[0, ]的和[i]。那么问题就变为:找到,, < ,[]-[]接近于并且小于。
从左向右扫描数组,把当前的[]值放入集合中。当处理[]时,从集合中检索大于[]-的最小元素,可以使用upper_bound函数在O(logN)时间内完成检索。所以整体复杂度为O(N*logN)。
C++代码
这里用C++ stl的set作为集合的容器,set中自带upper_bound方法。
![00fe8b5ed2bed6012fd96e1df4385eab.png](https://img-blog.csdnimg.cn/img_convert/00fe8b5ed2bed6012fd96e1df4385eab.png)
参考资料:
https://www.quora.com/Given-an-array-of-integers-A-and-an-integer-k-find-a-subarray-that-contains-the-largest-sum-subject-to-a-constraint-that-the-sum-is-less-than-k