返回信息流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: 5
max. 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: 0
In this case, no transaction is done, i.e. max profit = 0.
————————————————————————————————————————————————
class Solution {
public:
int maxProfit(vector<int>& prices) {
int low=prices[0];
int res=0;
for(int i=1;i<prices.size();i++)
{
if(prices[i]-low>res)
res=prices[i]-low;
else
low=prices[i];
}
return res;
}
};
————————————————————————————————————
Submission Result: Runtime Error
Runtime Error Message: reference binding to null pointer of type 'value_type'
Last executed input: []
这是一条镜像帖。来源:北邮人论坛 / cpp / #94859同步于 2017/3/13
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
哪里出了错!!
bingge
2017/3/13镜像同步3 回复
订阅后,新回复会通过你的通知中心匿名送达。
3 条回复
确实
加了一条if(prices.size()==0) return 0;
通过了
【 在 NachtZ 的大作中提到: 】
: 如果price是空数组你这程序就出错了。
你帖子复制的时候就已经把错误的样例复制出来了。leetcode出错的时候会把出错的那个case打出来的。这个提示已经很明显了。
【 在 bingge 的大作中提到: 】
: 确实
: 加了一条if(prices.size()==0) return 0;
: 通过了