Best Time to Buy and Sell Stocks I

Problem Description

Say you have an array, A, 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.

Return the maximum possible profit.


Problem Constraints

1 <= A[i] <= 1e7


Input Format
The first and the only argument is an array of integers, A.

Output Format
Return an integer, representing the maximum possible profit.

Example Input

Input 1:

A = [1, 2]
Input 2:

A = [1, 4, 5, 2, 4]


Example Output

Output 1:

1

Output 2:

4

Example Explanation

Explanation 1:

Buy the stock on day 0, and sell it on day 1.

Explanation 2:

Buy the stock on day 0, and sell it on day 2.

Solution:

Time: O(n)
Space: O(1)

public class Solution {
    // DO NOT MODIFY THE ARGUMENTS WITH "final" PREFIX. IT IS READ ONLY
    public int maxProfit(final int[] A) {
        int minSoFar = Integer.MAX_VALUE;
        int maxProfit = 0;
        for (int i = 0; i < A.length; i ++) {
            int curr = A[i];
            if (curr - minSoFar > maxProfit) {
                maxProfit = curr - minSoFar;
            }
            minSoFar = Math.min(minSoFar, curr);
        }
        return maxProfit;
    }
}

class Solution {
    // dp[i][s] = profit on day i with state (0 : no stock, 1 : has stock)
    // dp[i][0] = dp[i - 1][0], dp[i - 1][1] + p[i]
    // dp[i][1] = dp[i - 1][1], - p[i]
    // dp[0][0] = 0
    // dp[0][1] = -p[0]
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0) {
            return 0;
        }
        int n = prices.length;
        int[][] dp = new int[n][2];
        dp[0][0] = 0;
        dp[0][1] = -prices[0];
        for (int i = 1; i < n; i ++) {
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
            dp[i][1] = Math.max(dp[i - 1][1], - prices[i]);
        }
        return dp[n - 1][0];
    }
}

class Solution {
    // dp[i][s] = profit on day i with state (0 : no stock, 1 : has stock)
    // dp[i][0] = dp[i - 1][0], dp[i - 1][1] + p[i]
    // dp[i][1] = dp[i - 1][1], - p[i]
    // dp[0][0] = 0
    // dp[0][1] = -p[0]
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0) {
            return 0;
        }
        int n = prices.length;
        int[] dp = new int[2];
        dp[0] = 0;
        dp[1] = -prices[0];
        for (int i = 1; i < n; i ++) {
            dp[0] = Math.max(dp[0], dp[1] + prices[i]);
            dp[1] = Math.max(dp[1], - prices[i]);
        }
        return dp[0];
    }
}