1. 程式人生 > >Leetcode PHP題解--D109 122. Best Time to Buy and Sell Stock II

Leetcode PHP題解--D109 122. Best Time to Buy and Sell Stock II

D109 122. Best Time to Buy and Sell Stock II

題目連結

122. Best Time to Buy and Sell Stock II

題目分析

給定一個數組,代表商品價格。從給定的陣列中,計算通過買賣能獲得的最大收益。只有賣出才能再買入。

思路

一開始以為是獲取最小值右邊的最大值去賣出。

後來發現規律,是在價格拐點進行買入賣出操作。

即,先單調遞減後單調遞增時買入,先單調遞增後單調遞減時賣出。

最終程式碼

<?php
class Solution {

    /**
     * @param Integer[] $prices
     * @return Integer
     */
    function maxProfit($prices) {
        $profit = 0;
        $buyIndex = -1;
        $days = count($prices);
        $increasing = ($prices[0]<$prices[1]);
        if($increasing){
            $buyIndex = 0;
        }
        for($i=1; $i<$days; $i++){
            //if is increasing perviously
            if($increasing){
                //but starts to decrease
                //than its time to sell
                if($prices[$i]>$prices[$i+1]){
                    if($buyIndex != -1 ){
                        $profit += $prices[$i]-$prices[$buyIndex];
                    }
                    $buyIndex = $i+1;
                    $increasing = false;
                }
            }
            else{ //decreasing
                //starts 
                if($prices[$i]<$prices[$i+1]){
                    $buyIndex = $i;
                    $increasing = true;
                }
            }
        }
        return $profit;
    }
}

我個人認為這個函式並沒有使用很複雜的演算法,但是隻打敗了28.36%。記憶體佔用只打敗了15.79%。有很大的改進空間。

若覺得本文章對你有用,歡迎用