Lintcode. Best Time to Buy and Sell Stock I, II, III

Best Time to Buy and Sell Stock I

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example
Given array [3,2,3,1,2], return 1.

Python
Time complexity: O(N)
Space complexity: O(1)

class Solution:
    """
    @param prices: Given an integer array
    @return: Maximum profit
    """
    def maxProfit(self, prices):
        # write your code here
        if (not prices or len(prices) <= 1):
            return 0
            
        minSoFar = prices[0]
        profit = 0
        
        for v in prices[1:]:
            minSoFar = min(minSoFar, v)
            profit = max(profit, v - minSoFar)

        return profit

 

Best Time to Buy and Sell Stock II

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).

Example
Given an example [2,1,2,0,1], return 2.

Java
Time complexity: O(N)
Space complexity: O(1)

class Solution {
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     * As a solution one can find sum of contiguous delta trades, where 
     * 'delta trade' stands for buy-sell compound transaction.
     */
    public int maxProfit(int[] prices) {
        // write your code here
        if (prices == null || prices.length <= 0){
            return 0;
        }
        
        int profit = 0;
        
        for (int i = 1; i < prices.length; ++i){
            profit += Math.max(0, prices[i] - prices[i-1]);
        }
        
        return profit;
    }
}

 

Best Time to Buy and Sell Stock III

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 at most two transactions.

Notice : You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Example

Given an example [4,4,6,1,1,4,2,5], return 6.

Java
Time complexity: O(N)
Space complexity: O(1)

class Solution {
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    public int maxProfit(int[] prices) {
        // write your code here
        if (prices == null || prices.length == 0){
            return 0;
        }
        
        int buyFirst = Integer.MIN_VALUE;
        int sellFirst = 0;
        int buySecond = Integer.MIN_VALUE;
        int sellSecond = 0;
        
        for (int i = 0; i < prices.length; ++i){
            buyFirst = Math.max(buyFirst, -prices[i]);
            sellFirst = Math.max(buyFirst + prices[i], sellFirst);
            buySecond = Math.max(buySecond, sellFirst - prices[i]);
            sellSecond = Math.max(sellSecond, buySecond + prices[i]);
        }
        
        return sellSecond;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s