您的位置:首页 > 编程语言 > Go语言

leetcode: (121) Best Time to Buy and Sell Stock

2015-09-06 22:10 471 查看
【Question】

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.
思路,就是要找出后面值与前面值得最大差距

class Solution {
public:
int maxProfit(vector<int>& prices) {
int len =prices.size();
if(len<=1) return 0;
int buy;
int sell=0;
buy = prices[0];
int profit=0;
for(int i=1;i<len;i++)
{
sell=prices[i];
if(sell<buy) buy = sell;
else if(sell-buy>profit) profit=sell-buy;

}
return profit;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithms leetcode