Best Time to Buy and Sell Stock I
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.
Subscribe to see which companies asked this question
题目:给你每天股票的价格,求一次买入一次出手后的最大利润
1.从前往后遍历,0-i天买入,第i天出手时,最多可赚 prices[i] - low ,low是到第i天为止,最低的价格
class Solution {
public:
int maxProfit(vector<int>& prices) {
int ret=0;
if(prices.size()<=0)
return ret;
int low=prices[0];
for(int i=0;i<prices.size();i++){
low=low>prices[i]?prices[i]:low;
ret=(prices[i]-low)>ret?prices[i]-low:ret;
}
return ret;
}
};
2,转自 http://www.cnblogs.com/remlostime/archive/2012/11/06/2757434.html
class Solution { public: int maxProfit(vector<int> &prices) { // Start typing your C/C++ solution below // DO NOT write int main() function if (prices.size() == 0) return 0; int maxPrice = prices[prices.size()-1]; int ans = 0; for(int i = prices.size() - 1; i >= 0; i--) { maxPrice = max(maxPrice, prices[i]); ans = max(ans, maxPrice - prices[i]); } return ans; } };
Best Time to Buy and Sell Stock II
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
题意:可以买卖多次class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()<=1)
return 0;
int ret=0;
for(int i=0;i<prices.size()-1;i++){
int tmp=prices[i+1]-prices[i];
ret+=tmp>0?tmp:0;
}
return ret;
}
};
Best Time to Buy and Sell Stock III
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Best Time to Buy and Sell Stock I 中的计算方法求最大利润,再把两个最多利润相加
class Solution {
public:
int maxProfit(vector<int>& prices) {
int ret=0;
int len=prices.size();
if(len<=1)
return 0;
vector<int> flg1(len,0);//flg1[i] 表示【1-i】区间的最大利润
vector<int> flg2(len,0);//flg2[i] 表示【i-n】区间的最大利润
int max=prices[len-1];
int low=prices[0];
int cur=0;
for(int i=0;i<prices.size();i++){
low=low>prices[i]?prices[i]:low;
cur=(prices[i]-low)>cur?(prices[i]-low):cur;
flg1[i]=cur;
}
cur=0;
for(int i=len-1;i>=0;i--){
max=max>prices[i]?max:prices[i];
cur=(max-prices[i])>cur?max-prices[i]:cur;
flg2[i]=cur;
}
for(int i=0;i<len;i++){
ret=ret<flg1[i]+flg2[i]?flg1[i]+flg2[i]:ret;
}
return ret;
}
};
参考: http://www.tuicool.com/articles/rMJZj2