Best Time to Buy and Sell Stock
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
这道题一开始理解错了,以为是求一个数组中的最大最小值之差。后来想了想,发现股票卖出只能是在买入之后,所以这种想法显然是不对的。思考了一下,需要保存两个变量,一个是当前买入的最小值minprice,一个当前卖出的最大利润。新输入一个数,如果大于minprice,则有利润,求取当前利润,若大于最大利润,则更新最大利润。如果小于minprice,则更新买入值minprice。代码如下:
class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.size()<=1)
return 0;
int maxprofit=0,profit,minprice;
for(int i=0;i<prices.size();i++){
if(i==0)
minprice=prices[0];
if(prices[i]>=minprice){
profit=prices[i]-minprice;
if(profit>maxprofit)
maxprofit=profit;
}
else
minprice=prices[i];
}
return maxprofit;
}
};
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).
这道题一开始没有理解题意,发现最的英文水平真是烂的可以。大意就是从第一天开始,到结束那天可以多次买入可卖出股,但是每次手中最多只能持有一只股票。求经过多次交易,能获得的最大利益是多少。这样看来就简单了,只要第i+1天比第i天大,就买入第i天在第i+1天卖出。如果i+2天比第i+1天大,则在第i+1天卖出后在买入一只股票在第i+2天卖出,依次类推。
class Solution {
public:
int maxProfit(vector<int> &prices) {
int profit=0;
if(prices.size()<=1) return 0;
for(int i=1;i<prices.size();i++){
if(prices[i]>prices[i-1])
profit+=prices[i]-prices[i-1];
}
return profit;
}
};
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).
class Solution {
public:
int maxProfit(vector<int> &prices) {
int n=prices.size();
if(n<=1) return 0;
int lowestin=prices[0];
int highestout=prices[n-1];
vector<int> preincom;
preincom.push_back(0);//第一天收益为0
int profit=0,maxprofit=0;
int total=0,maxtotal=0;
for(int i=1;i<n;i++){
if(prices[i]>prices[i-1]){
profit=prices[i]-lowestin;
if(profit>maxprofit)
maxprofit=profit;
}
if(prices[i]<lowestin)
lowestin=prices[i];
preincom.push_back(maxprofit);
}
maxprofit=0;
for(int i=n-2;i>=0;i--){
if(prices[i]>highestout)
highestout=prices[i];
if(prices[i]<prices[i+1]){
profit=highestout-prices[i];
if(profit>maxprofit)
maxprofit=profit;
}
total=maxprofit+preincom[i];
if(total>maxtotal)
maxtotal=total;
}
return maxtotal;
}
};
题目中说的是至多两次,如果是制定交易次数必须为两次呢?