Fra*_*zur 6 javascript arrays algorithm
我正在做一个我无法解决的练习.我需要通过买卖比特币来获得最大的累积利润.我有一个函数(A,Y),它接收一个A =不同价格的数组,在时间和Y =费用限制:
注意:如果比特币在0买入并在1卖出,我们将失去A [1] - A [0] = 7050 -7200 - Y = -200.所以,没有做出这种运动.
注意2:您当时只能拥有1个比特币.要卖,你必须先买.要购买,您需要先购买或出售.
注3:运动需要时间结果.你不能在A [5]购买并在A [4]出售
注4:如果无法获利,则应返回0
复杂度是O(N)
A = [7200,7050,7300,7500,7440,7200,7300,7280,7400] //expected result 550
Y = 50
A[3] - A[1] - Y = 7500 - 7050 - 50 = 400
A[8] - A[5] - Y = 7400 - 7200 - 50 = 150
result = 550 //maximum accumulated profit
Run Code Online (Sandbox Code Playgroud)
这就是我所拥有的
function solution(A, Y) {
if(A.length < 2) {
return 0;
}
var minIndex = (A[0] > A[1]) ? 1 : 0;
var minPrice = A[minIndex];
var acum = 0;
var i = minIndex + 1
for (i; i< A.length-1; i++) {
if( (A[i] - minPrice - Y) > (A[i+1] - minPrice - Y )) {
acum += A[i] - minPrice - Y;
i = i+1
} else {
acum += A[i + 1] - minPrice - Y;
i = i+2
}
minPrice = (A[i] > A[i+1]) ? A[i+1] : A[i];
}
return acum > 0 ? acum : 0;
}
Run Code Online (Sandbox Code Playgroud)
实际上我得到450但应该是550
它看起来更复杂,因为你需要检查每一个买入价格和所有可能的卖出价格。
结果是一棵采用这种蛮力方法的树。
该解决方案仅返回所有买入/卖出价格的最大利润。
function maxima(array, fee) {
function iter(prices, index, count) {
var i = 0, profit = 0;
if (index >= array.length) {
if (!prices.length || prices.length % 2) {
return;
}
if (prices.some((v, i, a) => i && (i % 2 ? a[i - 1] >= v : a[i - 1] < v))) {
return;
}
while (i < prices.length) {
profit += prices[i + 1] - prices[i] - fee;
i += 2;
}
if (!result.length || result[0].profit < profit) {
result = [{ profit, prices }];
} else if (result[0].profit === profit) {
result.push({ profit, prices });
}
return;
}
iter(prices.concat(array[index]), index + 1); // buy/sell
iter(prices, index + 1); // no action
}
var result = [];
iter([], 0, 0);
return result;
}
console.log(maxima([7200, 7050, 7300, 7500, 7440, 7200, 7300, 7280, 7400], 50));Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
309 次 |
| 最近记录: |