algorithm - 通过数组值的加法和减法找到可能的最大值而不重叠
问题描述
输入
给定一个array
,一个maximum
值和一个current
值。
目标
对于每个i
in array[i]
,都array[i]
必须加上或减去current
。我无法确切知道何时应该添加或减去以获得以下output
.
输出
电流在不高于maximum
或低于 0 的情况下可能获得的最高值。如果不可能,则返回 -1。
问题
我想出了以下代码段,但它不正确。如果我计算每个可能的答案,然后找到最大的答案,那么复杂度就会高于 O(n)。我怎么知道什么时候减或加?
function calcMax(array, max, current) {
let output = current;
for (let i = 0; i < array.length; i++) {
if (output + array[i] <= max) {
output += array[i];
} else {
output -= array[i];
}
return output < 0 ? -1 : output;
}
}
console.log(calcMax([5, 3, 7], 16, 5))
例子
输入:([15, 2, 9, 10], 20, 8)。正确输出:-1
输入:([5, 3, 7], 10, 5)。正确输出:10 (5 - 5 + 3 + 7)
输入:([5, 3, 7], 16, 5)。正确输出:14 (5 + 5 - 3 + 7)
解决方案
我想出了一个递归解决方案。我认为是 O(n)。
const max = 50;
const current = 20
const array = [20, 30, 4, 14, 16];
let answer = -1;
function calcMax(i, value) {
// Checking the bounds
if (i === array.length) {return value}
if (value > max || value < 0) {return -1}
// With each index compare it with final answer
let r = 0;
if (value + array[i] <= max) {
r = calcMax(i + 1, value + array[i]);
if (r > answer) {
answer = r;
}
}
if (value - array[i] >= 0) {
r = calcMax(i + 1, value - array[i]);
if (r > answer) {
answer = r;
}
}
return r;
}
calcMax(0, current);
console.log(answer);
推荐阅读
- symfony4 - 如何在 Sulu 中向导航添加外部链接
- python-3.x - Python 3 ~ 如何从 csv 文件中获取行并将它们放入列表中
- python - 有没有更简单的方法可以根据这些信息创建 df?
- javascript - 未注册的类切换
- python - 神经网络; 模型结果有问题
- python - Python:使用 scipy.spatial.transform.Rotation 旋转平面(点集)以匹配新的法线向量
- docker - 如何测试容器之间的连接?
- php - 在 Blazor ServerSide 应用程序中登录会话
- python-3.x - 不断收到AttributeError:'str'对象没有属性'items'
- wordpress - 如何使用 wordpress 和 elementor 在产品存档页面中显示自定义 ACF 产品标签?