本文主要是介绍LeetCode 121. Best Time to Buy and Sell Stock,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
121. Best Time to Buy and Sell Stock
一、问题描述
Say you have an array for which the i*th 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.
二、输入输出
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)
Input: [7, 6, 4, 3, 1]
Output: 0In this case, no transaction is done, i.e. max profit = 0.
三、解题思路
- 后面会有这道题的变体版,针对这个Easy版本,只需要双重遍历数组,记录并更新maxProfit即可
- 这里只能买卖1次股票使得问题变的非常简单
class Solution {
public:int maxProfit(vector<int>& prices) {int maxProfit = 0, n = prices.size();for (int i = 0; i < n; ++i) {int buyP = prices[i];for (int j = i + 1; j < n; ++j) {if (prices[j] <= buyP) continue;if (prices[j] - buyP > maxProfit)maxProfit = prices[j] - buyP;}}return maxProfit;}
};
这篇关于LeetCode 121. Best Time to Buy and Sell Stock的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!