Thursday, January 11, 2018

[2018-Interview] Best Time to Buy and Sell Stock II

Original question: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/

Logic: take any chance of making a profit to sell and buy. This can make max profit. You can sell and buy in the same day. If you can not buy and sell in same day, solution would be different. We can explore it later.

My answer:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
    public int maxProfit(int[] prices) {
        int maxProfit = 0;
        if (prices == null || prices.length < 2) {
            return maxProfit;
        }
        for (int buyInIndex = 0; buyInIndex < prices.length - 1; buyInIndex ++) {
            if (prices[buyInIndex] < prices[buyInIndex + 1]) {
                maxProfit +=  prices[buyInIndex + 1] - prices[buyInIndex];
            }
        }
        return maxProfit;
    }
}

No comments:

Post a Comment