The best time to buy and sell stocks II

Time:2020-10-10

Given an array, its i-th element is the price of a given stock on day I.

Design an algorithm to calculate the maximum profit you can make. You can do as many trades as you can.
Note: you cannot participate in more than one transaction at the same time (you must sell the previous stock before buying again).

Example 1:
Input: [7,1,5,3,6,4]
Output: 7
Explanation: if you buy on day 2 (stock price = 1) and sell on day 3 (stock price = 5), the exchange can make a profit = 5-1 = 4.
     Then, buy on day 4 (stock price = 3) and sell on day 5 (stock price = 6), the exchange can make a profit = 6-3 = 3.
Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: if you buy on day 1 (stock price = 1) and sell on day 5 (stock price = 5), the exchange can make a profit = 5-1 = 4.
     Note that you can't buy shares one day after another and sell them later.
     Because this is involved in multiple transactions at the same time, you have to sell the previous stock before buying again.
Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: in this case, the transaction is not completed, so the maximum profit is 0.

Tips:
    1 <= prices.length <= 3 * 10 ^ 4

Greedy algorithm 1

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    var maxproft = 0
    for(var i =0;i<prices.length;i++){
        if(prices[i]>prices[i-1] ){
            maxproft+=prices[i]-prices[i-1]
        }
    }
    return maxproft
};

Greedy algorithm 2

var maxProfit = function (prices) {
    var maxproft = 0
    for (var i = 0; i < prices.length; i++) {
        maxproft += Math.max(0, prices[i] - prices[i - 1])
    }
    return maxproft
};

Recommended Today

JS function

1. Ordinary function Grammar: Function function name (){ Statement block } 2. Functions with parameters Grammar: Function function name (parameter list){ Statement block } 3. Function with return value Grammar: Function function name (parameter list){ Statement block; Return value; } Allow a variable to accept the return value after calling the function Var variable name […]