2.1 Best Time to Buy and Sell Stock II

Description

Say you have an array 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 (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Method

It is a little tricky. Since you can make multiple transactions, it means that you can buy one share and sell it immediately. So you can earn profit when there has a price difference.

eg : 4 8 2 6 8 9 buy sell buy sell/ buy agian sell/ buy agian sell

so the max profit is the sum for all increasing price differences

Time and Space Complexity

o(n)

Code

public class Solution {

public int maxProfit(int[] prices) {
    if (prices == null || prices.length == 0){
        return 0;
    }    
    int total = 0;
    for (int i = 1; i < prices.length; i++){
        if (prices[i] > prices[i - 1]){
             total += prices[i] - prices[i - 1];
        }
    }
    return total;
}

}

results matching ""

    No results matching ""