动态规划——121. Best Time to Buy and Sell Stock[easy]

来源:互联网 发布:魔幻壁纸软件 编辑:程序博客网 时间:2024/06/14 18:29

题目描述

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.

输入一个股票价格数组,要求在买卖之间获利最多,且注意,买应该在卖之前,卖价格低于买价格时不卖,且只有一次交易机会。


解题思路


设prices[i]为当前价格,我应该在0~i之间最低买,在i卖,而且如此循环更新我的profit。所以,先遍历0~i得出最小值,然后如果在i卖出获利大于当前profit,则更新profit。

而且遍历得到最小值和更新profit是可以在同一个循环里完成的,min只在prices[i]< min时更新


代码如下


class Solution {public:  int maxProfit(vector<int>& prices) {if (prices.empty())return 0;int minUtilNow = prices[0];int maxUtilNow = 0;for (int i = 1; i < prices.size(); i++) {if (minUtilNow > prices[i]) {minUtilNow = prices[i];}if (prices[i] - minUtilNow > maxUtilNow) {maxUtilNow = prices[i] - minUtilNow;}}return maxUtilNow;}};


0 0