本文主要是介绍LeetCode *** 121. Best Time to Buy and Sell Stock,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
Say you have an array for which the ith element is the price of a given stock on dayi.
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.
分析:
买入价一定是前面比较低的,那么就可以直接考虑记录买入价,直到找到一个价钱比当前买入价更低的,然后继续进行加减。这道题我觉得出的还可以。
代码:
class Solution {
public:int maxProfit(vector<int>& prices) {int res=0,minP=INT_MAX;int len=prices.size();for(int i=0;i<len;++i){if(minP>prices[i])minP=prices[i];if(res<prices[i]-minP)res=prices[i]-minP;}return res;}};
这篇关于LeetCode *** 121. Best Time to Buy and Sell Stock的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!