JavaScript   发布时间:2022-04-16  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了javascript – 返回最大累计利润大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在做一个我无法解决的练习.我需要通过买卖比特币来获得最大的累积利润.我有一个函数(A,Y),它在时间和Y =费用中接收A =不同价格的数组
限制:

注意:如果比特币在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,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

这就是我所拥有的

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;
}

实际上我得到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);
    return result;
}

console.log(maxima([7200,7400],50));
.as-console-wrapper { max-height: 100% !important; top: 0; }

大佬总结

以上是大佬教程为你收集整理的javascript – 返回最大累计利润全部内容,希望文章能够帮你解决javascript – 返回最大累计利润所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: