Blog Details

Best time to buy and sell stock – one time transaction

1. Description

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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

2. Example

Input: [7, 1, 5, 3, 6, 4]
Output: 5. 
Explanation: Buy at day 2, which value is 1. and sell it on day 5. 6-1=5. 

3. Solution

Apply Brute Force Alg, loop each price, and find the max profit value.

class Solution {
    public int maxProfit(int[] prices) {
        int maxProfit = 0;
        for(int i = 0; i < prices.length - 1; i ++) {
            for(int j = i + 1; j < prices.length; j ++) {
                int profit = prices[j] - prices[i];
                if(profit > maxProfit) {
                    maxProfit = profit;
                }
            }
        }
        return maxProfit;
    }
}

4. Complexity

Time Complexity: O(n)

Space complexity: O(1)