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.
只做一次交易:
贪心算法(最小买进,最大卖出,卖出时间比买进时间大):
int maxProfit(vector<int> &prices) {
if(prices.size()<2)
return 0;
int min_cur =prices[0],profit =0;
for(int i=1;i<prices.size();i++)
{
if(prices[i]-min_cur>profit)
{
profit =prices[i]-min_cur;
}
min_cur =min(prices[i],min_cur);
}
return profit;
}
Best Time to Buy and Sell Stock II Total Accepted: 20291 Total Submissions: 55090 My Submissions
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).
int maxProfit(vector<int> &prices) {
int sum =0;
for(int i=1;i<prices.size();i++){
int diff =prices[i] -prices[i-1];
if(diff>0) sum+=diff;
}
return sum;
}
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).
最多两次交易
int valley,peak;
int maxProfit(vector<int> &prices) {
if(prices.size()<2)return 0;
const int n=prices.size();
vector<int> f(n,0);
vector<int> g(n,0);
for(int i=1,valley =prices[0];i<n;i++)
{
valley =min(valley,prices[i]);
f[i] =max(f[i-1],prices[i] -valley);
}
for(int i=n-2,peak=prices[n-1];i>=0;--i)
{
peak =max(peak,prices[i]);
g[i] =max(g[i],peak -prices[i]);
}
int max_profit =0;
for(int i=0;i<n;++i)
{
max_profit =max(max_profit,f[i]+g[i]);
}
return max_profit;
}
};