Best Time to Buy and Sell Stock

[Question]: In an array of prices where prices[i] is the price of a given stock on an ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Approach #1

Use a buy price variable which is possibly with a max value, difference variable is something like day when we are selling the stock (sell-buy)

func maxProfit(arr: [Int]) -> Int {
    var buyPrice = Int.max
    var difference = 0
    
    for i in 0..<arr.count {
        if arr[i] < buyPrice {
            buyPrice = arr[i]
        }
        if difference < (arr[i] - buyPrice) {
            difference = arr[i] - buyPrice
        }
        // OR.
        /**
        minPrice = min(minPrice, arr[i]);
        maxPro = max(maxPro, arr[i] - minPrice);
         */
    }
    return difference
}

var stockArray = [7, 1, 5, 3, 6, 4]
let profitMax = maxProfit(arr: stockArray)
print("The maxProfit  is:", profitMax)// 5

Leave a Comment

Your email address will not be published. Required fields are marked *