非递减序列的最大和
例如。 -3,6,11,13,5,-11,4,7,8最大和=30(6,11,13因为加上-3会使和更小)
例如7,0,-3 最大总和 = 7
例如 4,-1,45 最大总和 = 45
例如 -3-,-2,-6,0 最大总和 =0
需要对我的代码提出一些建议,仍然有问题
int maxSum = Integer.MIN_VALUE;
int sum = 0;
int checkNeg = Integer.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
if (a[i] > checkNeg) {
checkNeg = a[i];
}
}
if (checkNeg <= 0) {
maxSum = checkNeg;
}
if (checkNeg > 0) {
for (int i = 0; i < a.length; i++) {
if (a[i] != 0) {
sum += a[i];
if (sum > maxSum) {
if (i != 0) {
if (a[i] >= a[i - 1]) {
maxSum = sum;
} else {
sum = a[i];
}
} else {
maxSum = sum;
}
}
if (sum < 0) {
sum = 0;
}
} else {
sum = 0;
}
}
}
return maxSum;
eg. -3,6,11,13,5,-11,4,7,8 largest sum =30 (6,11,13 cause adding -3 will make the sum smaller)
eg. 7,0,-3 largest sum = 7
eg 4,-1,45 largest sum = 45
eg -3-,-2,-6,0 largest sum =0
Need some advise for my code, still buggy
int maxSum = Integer.MIN_VALUE;
int sum = 0;
int checkNeg = Integer.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
if (a[i] > checkNeg) {
checkNeg = a[i];
}
}
if (checkNeg <= 0) {
maxSum = checkNeg;
}
if (checkNeg > 0) {
for (int i = 0; i < a.length; i++) {
if (a[i] != 0) {
sum += a[i];
if (sum > maxSum) {
if (i != 0) {
if (a[i] >= a[i - 1]) {
maxSum = sum;
} else {
sum = a[i];
}
} else {
maxSum = sum;
}
}
if (sum < 0) {
sum = 0;
}
} else {
sum = 0;
}
}
}
return maxSum;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试一下这
似乎适用于您的所有示例和其他几个示例。
不需要“checkNeg”,这个检查应该更自然地从算法中出来
Try this
seemed to work for all your examples and a couple of others.
There is no need for 'checkNeg', this check should come out of the algorithm a little more naturally