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).
給定陣列,代表每天的股價,交易次數不限,最多能賺多少錢?
Input: [7,1,5,3,6,4]
Output: 7
Input: [1,2,3,4,5]
Output: 4
只要當天價格比昨天高,就表示有獲利,將獲利加總,就是我們要的答案
var maxProfit = function (prices) {
let Profit = 0;
for (let i = 1; i < prices.length; i++) {
if (prices[i - 1] < prices[i]) {
Profit += (prices[i] - prices[i - 1]);
}
}
return Profit;
};