メインコンテンツへスキップ

NeetCode 150 [Sliding Window]:easy

· loading · loading ·
kiitosu
著者
kiitosu
画像処理やデバイスドライバ、データ基盤構築からWebバックエンドまで、多様な領域に携わってきました。地図解析や地図アプリケーションの仕組みにも経験があり、幅広い技術を活かした開発に取り組んでいます。休日は草野球とランニングを楽しんでいます。
目次

NeetCodeのSolutionを書いていく
#

Best Time to Buy and Sell Stock
#

株価を想定した、整数の配列を渡されるので、安いときに買って高いときに売る。 最高の利益を出せばOK。 明記されていないけど、複数回売り買いしていいのかな?

[7,1,5,3,6,4] の場合、複数回売り買いした時の最適値は(5-1)+(6-3)で7なので1回だけみたい。

ポイントは売るときに未来の値段では買えないことくらいかな?

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        buy = 100
        profit = 0
        for price in prices:
            if buy > price:
                buy = price
            if profit < price - buy:
                profit = price - buy
            print(price, buy, profit)
        return profit

いけたー。 最初に問題設定を読み誤って(明記されていない?)すこ手こずってしまった。 問題設定確認とアルゴリズムの事前検討大事。

Reply by Email

関連記事

NeetCode 150 [Trees]:easy 2/3
· loading · loading
NeetCode 150 [Two Pointers]:easy
· loading · loading
NeetCode 150 [Trees]:easy 3/3
· loading · loading