leetcode. Best Time to Buy and Sell Stock

來源:互聯網
上載者:User

標籤:des   style   blog   io   ar   color   os   使用   sp   

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.

首先,問題轉換為數學語言:對數組A[n], 對任意i < j < n, 求出max(A[j] - A[i]).

可以使用O(n^2)的方法得到結果。

以下分析動態規劃方法:

對於輸入prices[n], 如果已知profit[i - 1], 

1) 當prices[i] <= prices[i - 1]時,顯然,profit[i] = profit[i - 1]

2)當prices[i] > prices[i - 1]時, 記bottom = min(prices[0, 1, ..., i]), 如果

prices[i] - bottom > profit[i - 1] 則有
profit[i] = prices[i] - bottom

否則,profit[i] = profit[i - 1]
 1 int maxProfit(vector<int> &prices)  2     { 3         int n = prices.size(), bottom, max_profit; 4         if (n <= 1) 5             return 0; 6         int *profit = new int[n]; 7         profit[0] = 0; 8         bottom = prices[0]; 9         for (int i = 1; i < n; i++)10         {11             bottom = min(bottom, prices[i]);12             if (prices[i] > prices[i - 1] && prices[i] - bottom > profit[i - 1])13             {14                 profit[i] = prices[i] - bottom;15             }16             else17             {18                 profit[i] = profit[i - 1];19             }20         }21         max_profit = profit[n - 1];22         delete profit;23         return max_profit;24     }

 

leetcode. Best Time to Buy and Sell Stock

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.