2023年8月31日 星期四

【LeetCode】【Kotlin】Array (121. Best Time to Buy and Sell Stock) 解題紀錄

 想法

以Array、指標為出發,由左至右探索。
為求最大利益,需要使左指針所指向的值最小,右指針最大。
若發現右指針所指向的值小於左指針的,則將左指針改指向它的位置,而右指針繼續往下一個位置探索。
若右指針所指向的值沒有小於左指針的,則計算兩者差距,看有沒有超過原先紀錄的最大利益。

程式碼


class Solution {
    fun maxProfit(prices: IntArray): Int {
        var maxPorfit = 0
        var leftValue = prices[0]
        for (i in 1..prices.size-1){
            if(leftValue > prices[i]){
                leftValue = prices[i]
            }else{
                if(prices[i]-leftValue > maxPorfit) maxPorfit = prices[i]-leftValue
            }
        }
        return maxPorfit
    }
}

454ms / 56.09MB (beats 91.99% /45.08%)

0 comments:

張貼留言