您的位置:首页 > 其它

leetcode121---Best Time to Buy and Sell Stock

2015-05-28 17:41 330 查看
问题描述:

Say you have an array for which the ith element is the price of a given stock on day i.

给你一个数组,里边的第i个元素存储的是股票在第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.

只允许最多完成一次交易(买一股卖一股股票),设计算法找出最大收益。

问题求解:

利用贪心法求解。此题就是选择买入卖出股票的最大收益,分别找到价格最低和最高的一天,低进高出即可,也即找到最大增长,但是最低的一天要在最高的一天之前。时间复杂度为:O(N)。

class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if(n <= 1){
return 0;
}
//初始化最低价格
int minimum = prices[0];
//初始化最大收益
int max_profit = 0;
for(int i=1;i<n;i++){
//从前往后,当前收益用当前价格减去此前的最低价格
int profit = prices[i] - minimum;
//更新最大收益
max_profit = profit>max_profit?profit:max_profit;
//更新最低价格
minimum = prices[i]<minimum?prices[i]:minimum;
}
return max_profit;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息