1. 程式人生 > ><LeetCode OJ> 121. /122. Best Time to Buy and Sell Stock(I / II)

<LeetCode OJ> 121. /122. Best Time to Buy and Sell Stock(I / II)

今天 tar article 必須 font details let have 獲得

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.



分析:

思路首先:動態規劃
遍歷數組時記錄當前價格曾經的最小價格curMin,記錄昨天可以獲得的最大利潤maxProfit
對於今天,為了能獲得此刻的最大利潤,顯然僅僅能賣,或者不做不論什麽操作
假設不做不論什麽操作。顯然還是昨天maxProfit
假設賣掉今天天的股票。顯然prices[i]-curMin


class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size()<=1)
            return 0;
        int curMin=prices[0];
        int maxProfit=0;
        for(int i=1;i<prices.size();i++)
        {
            maxProfit=max(maxProfit,prices[i]-curMin);
            curMin=min(curMin,prices[i]);//獲得歷史最小價格的股票
        }
        return maxProfit;
    }
};




Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like

(ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time

(ie, you must sell the stock before you buy again).

同一時間不能做多次交易(買一次再賣一次,或者賣一次再買一次算一次交易)。意思就是說在你買股票之前你必須賣掉股票

(即你手頭最多同意保留一僅僅股票。同一時候隱含了每次僅僅能交易一次的意思)


分析:

題目理解錯誤,剛開始沒有不論什麽思路....這題通過率40%。我的內心是崩潰的!

!!


題目:用一個數組表示股票每天的價格,數組的第i個數表示股票在第i天的價格。設計一個算法找出最大利潤
但一次僅僅能交易一支股票,也就是說手上最多僅僅能持有一支股票,求最大收益。
分析:貪心法。從前向後遍歷數組,僅僅要當天的價格高於前一天的價格(即為了最大利潤,僅僅要有利潤存在就利用交易次數的無限制貪心的獲取)。就累加到收益中。
代碼:時間O(n),空間O(1)。

class Solution {  
public:  
    int maxProfit(vector<int>& prices) {  
        if(prices.size() < 2)   
            return 0;    
        int profit = 0;    
        for(auto ite = prices.begin()+1; ite != prices.end(); ite++)   
            profit += max(*ite - *(ite-1),0);    
        return profit;    
    }  
}; 



註:本博文為EbowTang原創,興許可能繼續更新本文。假設轉載,請務必復制本條信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50524380

原作者博客:http://blog.csdn.net/ebowtang

&lt;LeetCode OJ&gt; 121. /122. Best Time to Buy and Sell Stock(I / II)