Best Time to Buy and Sell Stock

This easy LC problem is just a reword or a variation of a problem that finds a pair with the maximum difference. This can be solved in O(n) because we can calculate the mininum number and maximum difference at the same time as we go through each of the array elements.

class Solution {
    fun maxProfit(prices: IntArray): Int {
        if(prices.isEmpty()) return 0
        
        var min = prices[0]
        var max = Integer.MIN_VALUE
        
        for(index in 1 until prices.size){
            max = Math.max(max, prices[index] - min)
            min = Math.min(min, prices[index])
        }
        
        return if(max >=0) max else 0
    }
}
Runtime: 168 ms, faster than 94.61% of Kotlin online submissions for Best Time to Buy and Sell Stock.
Memory Usage: 36.3 MB, less than 100.00% of Kotlin online submissions for Best Time to Buy and Sell Stock.