class Solution {
public:
int maxProfit(vector<int>& prices)
{
int smallest = prices[0];
int profit=0;
for(int i=1;i<prices.size();i++)
{
int diff=0;
if(prices[i]>smallest)
diff = prices[i]-smallest;
else
smallest = prices[i];
if(diff > profit)
profit=diff;
}
return profit;
}};问题)假设您有一个数组,其中ith元素是第一天给定股票的价格。
如果你最多只能完成一笔交易(即买一股,卖出一股),那就设计一个算法来找出最大的利润。
注意,在你买股票之前,你不能卖出一只股票。
示例1:
输入: 7,1, 5 ,3, 6,4输出:5解释:在第2天买进(价格= 1),在第5天卖出(价格= 6),利润= 6-1 =5,而不是7-1 =6,因为销售价格需要大于买入价格。
示例2:
输入: 7,6,4,3,1输出: 0解释:在本例中,没有完成任何事务,即最大利润=0。
我发现了一个错误:
reference binding to null pointer of type 'value_type' (stl_vector.h)发布于 2019-09-29 22:11:33
因此,其中一个测试用例有空向量作为input.Hence,当我试图在第一行访问价格时,它抛出了错误。因此,我添加了一个check-> if(prices.empty())返回0;结果证明答案是正确的。
https://stackoverflow.com/questions/58159212
复制相似问题