2021年6月27日 星期日

[122] Best Time to Buy and Sell Stock II

怎麼又寫起了Leetcode了呢~~~~~
久未寫, 寫起來果然是礙手礙腳的. 還因為蠢bug看半天= =
修了一下難得submit是過的!而且不算慢~
但對比最佳解還是有很長一段路要走, 哈!

int maxProfit(int* prices, int pricesSize)
{
    int profit = 0;
    int i = 0;
    int stockBuy=prices[0];
    if (pricesSize <= 1)
        return profit;
    for (i=0; i < pricesSize-1; i++)
    {
        if(prices[i+1] < prices[i] )         
        {
            if(prices[i]-stockBuy > 0)
                profit += prices[i] - stockBuy;
            stockBuy = prices[i+1];
        }
        else if ((i+1) == (pricesSize-1))
        {
            profit = profit + (prices[i+1] - stockBuy);               
            return profit;
        }
    }
    return profit;
}