LeetCode符号化問題2020年/12/14-最適BuyとSell Stock II


[質問]


Say you have an array prices for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

(要約)配列前の要素から行い、株を買うように、小さい数字の中でそれより大きい数字に遭遇した場合、差異の和を累積します.

[回答]

var maxProfit = function(prices) {
  const length = prices.length;
  let profit = 0;
  let buy = Math.max(...prices);
 
  for(let i = 0; i < length - 1; i++) {
    buy = prices[i] < buy ? prices[i] : buy;

    if(buy < prices[i + 1]) {
      profit += prices[i + 1] - buy;
      buy = prices[i + 1];
    }
  }

  return profit;
};
配列内の最大数を検索し、index0からループを開始し、現在の数値より小さい場合は数値を割り当てます.次の要素が数値より大きい場合は、数値の違いが累積されます.