当前位置:网站首页>小于等于K的最大子数组累加和
小于等于K的最大子数组累加和
2022-07-27 02:19:00 【小卢要刷力扣题】
题目
请返回arr中,求子数组的累加和,是<=K的并且是最大的
返回这个最大的累加和
解题思路

假设0~ 57整体累加和1000,求< =300的累加和怎么最大
其实就是求之前有哪个前缀和是>=700且最接近
1)0-0看有没有>=700的前缀和,没有,前缀和为40
2)0-1看有没有>=700的前缀和,没有,前缀和为100
3)0-2看有没有>=700的前缀和,没有,前缀和为70
…
n)0-23前缀和为710
即24-57的累加和为小于等于300最大的累加和
用有序表存储数据,可以拿到离700最近的数字
代码
public static int getMaxLessOrEqualK(int[] arr, int K) {
// 记录i之前的,前缀和,按照有序表组织
TreeSet<Integer> set = new TreeSet<Integer>();
// 一个数也没有的时候,就已经有一个前缀和是0了
set.add(0);
int max = Integer.MIN_VALUE;
int sum = 0;
// 每一步的i,都求子数组必须以i结尾的情况下,求个子数组的累加和,是<=K的,并且是最大的
for (int i = 0; i < arr.length; i++) {
sum += arr[i]; // sum -> arr[0..i];
if (set.ceiling(sum - K) != null) {
max = Math.max(max, sum - set.ceiling(sum - K));
}
set.add(sum); // 当前的前缀和加入到set中去
}
return max;
}
边栏推荐
- Network security / penetration testing tool awvs14.9 download / tutorial / installation tutorial
- Volatile keyword and its function
- Application, addition and deletion of B-tree
- [common search questions] 111
- easyui中textbox在光标位置插入内容
- 基于OpenCV的轮廓检测(1)
- MySQL中文失败问题
- Reading notes of Kazuo Inamori's advice to young people
- Number of 0 at the end of factorial
- Machine learning [Matplotlib]
猜你喜欢

MySQL has a nonexistent error

Connman introduction

MySQL的数据库有关操作

Okaleido tiger is about to log in to binance NFT in the second round, which has aroused heated discussion in the community

Briefly sort out the dualpivotquicksort

Redis spike case, learn from Shang Silicon Valley teacher in station B

How to optimize MySQL

Add support for @data add-on in idea

flask_ Reqparse parser inheritance in restful

Contour detection based on OpenCV (2)
随机推荐
次轮Okaleido Tiger即将登录Binance NFT,引发社区热议
A new paradigm of distributed deep learning programming: Global tensor
The function and application of lpci-252 universal PCI interface can card
Tool class of localdatetime sorted out by yourself
Permutation and binary (Ji, DA) (day 84)
MySQL的数据库有关操作
On the first day of Shenzhen furniture exhibition, the three highlights of Jin Ke'er booth were unlocked!
MySQL中文失败问题
Spark: ranking statistics of regional advertising hits (small case)
若依的环境的部署以及系统的运行
明汯投资裘慧明:长期优异超额的背后考验的是团队的投研能力和策略的完整性
MySQL Chinese failure
How to conduct 360 assessment
ZJCTF_ login
【树链剖分】2022杭电多校2 1001 Static Query on Tree
It's confirmed that the registration of soft exam in the second half of 2022 will start in August
Plato farm brings a new experience to community users through the LAAS protocol elephant swap
How to interact with the server when the client sends an SQL message
Maximum continuous subsequence (day 77)
榕树贷款C语言结构体里的成员数组和指针