题目
![]()
思路
一开始差点被绕进去,后来发现其实是第i个值和i+1的值的差计算。那就只要2个2个的计算出差,最后取反累加大于0的值就可以计算出最大收益了。
(其实倒序计算就可以不用取反2333)
答案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
var maxProfit = function(prices) { var diffPrice = [] ,i = 0 ,sumValue = 0; for(i;i < prices.length - 1;i++){ diffPrice.push( -(prices[i] - prices[i+1]) ); } diffPrice.forEach(function(value,index){ if(value > 0) sumValue += value; }) return sumValue; };
var maxProfit = function(prices) { var i = prices.length - 1 ,deffNum = 0 ,sumValue = 0; for(i;i > 0;i--){ if( (deffNum = prices[i] - prices[i-1]) > 0) sumValue += deffNum; } return sumValue; };
|