中山大学算法课程题目详解(第九周)

来源:互联网 发布:胡克霍根身体数据 编辑:程序博客网 时间:2024/06/05 20:46

问题描述:

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.

Example 1:

Input: [7, 1, 5, 3, 6, 4]Output: 5max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1]Output: 0In this case, no transaction is done, i.e. max profit = 0.

解决思路:

此题就是选择买入卖出股票的最大收益,对于第i天卖出的最大收益即为第i天的股市价格减去[0,i-1]天内的最小股市价格,当第i天的股市价格比漆面最低股市价格还低,则更新最低股市价格。然后取最大的股市收益,为DP问题。用profit[i]表示第i天的收益,则minBuyPrice = min(minBuyPrice, prices[i]),并且profit[i] = prices[i]-minBuyPrice. 然后取profit中的最大值。

代码实现:

int maxProfit(vector<int>& prices) {if (prices.size() == 0) {return 0;}int maxprofit = 0;int minPrice = prices[0];for (int i = 1; i < prices.size(); i++) {minPrice = min(minPrice, prices[i]);if (maxprofit < (prices[i] - minPrice)) {maxprofit = prices[i] - minPrice;}}return maxprofit;}


原创粉丝点击