149 · Best Time to Buy and Sell Stock - LintCode

# Description

Say you have an array for which the _i_th 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

Example 1

Input: [3, 2, 3, 1, 2]
Output: 1
Explanation: You can buy at the third day and then sell it at the 4th day. The profit is 2 - 1 = 1

Example 2

Input: [1, 2, 3, 4, 5]
Output: 4
Explanation: You can buy at the 0th day and then sell it at the 4th day. The profit is 5 - 1 = 4

Example 3

Input: [5, 4, 3, 2, 1]
Output: 0
Explanation: You can do nothing and get nothing.

# Code

public class Solution {
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    public int maxProfit(int[] prices) {
       int max = 0;
       int min = Integer.MAX_VALUE;
       for (int i = 0; i < prices.length; i++) {
	       // 假設今天歷史最低價
           if (prices[i] < min) {
               min = prices[i];
           } else if (prices[i] - min > max) {
           // 今天 $$$ - 最小值
               max = prices[i] - min;
           }
       }
       return max;
    }
}

# DP

public int maxProfit(int[] prices) {
        // dp[i] : max profit when we sell the stock at ith day => dp[k], 1<=k <=n
        // dp[i] = prices[i] - min price before i
        //dp [i] = dp [i - 1] + prices [i] - prices [i-1] 或 prices [i] - prices [i - 1]  (差價)
        if (prices.length == 0) return 0;
        int[] dp = new int[prices.length];
        int max_profit = 0;
        for (int i = 1; i < prices.length; i++) {
            dp[i] = Math.max(dp[i - 1] + prices[i] - prices[i - 1],
                                 prices[i] - prices[i - 1]);
            max_profit = Math.max(max_profit, dp[i]);
        }
        return max_profit;
    }
}