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) {
if(prices.size()==0)
return 0;
int minp=prices[0], maxpro=0;
for(int i=0; i<prices.size(); ++i){
minp=min(minp, prices[i]);
maxpro=max(maxpro, prices[i]-minp);
}
return maxpro;
}
};
即保存当前的最小元素和最大收益,并一直更新它们即可。
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) {
int profit=0;
for(int i=1; i<prices.size(); i++){
if(prices[i]>prices[i-1])
profit+=prices[i]-prices[i-1];
}
return profit;
}
};
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) {
if(prices.size()==0)
return 0;
vector<int> mp;
vector<int> mp_reverse;
mp.assign(prices.size(), 0); //初始化vector长度和初始值
mp_reverse.assign(prices.size(), 0); //初始化vector长度和初始值
int minp=prices[0], res=0;
for(int i=0; i<prices.size(); ++i){
minp=min(minp, prices[i]);
if(i>0)
mp[i]=max(mp[i-1], prices[i]-minp);
}
int maxp=prices[prices.size()-1];
for(int i=prices.size()-1; i>=0; i--){
maxp=max(maxp, prices[i]);
if(i<prices.size()-1){
mp_reverse[i]=max(mp_reverse[i+1], maxp-prices[i]);
}
res=max(res, mp[i]+mp_reverse[i]);
}
return res;
}
};