最佳买卖点:
写的啥,太复杂了
/*
thinking:
1.get the smaller num to buy,
2.assume cur num to buy if next is smaller ,not buy,
3.when cur<before, cur<next buy,
================
for each num:
buy or not: not bought ,< pre,<next
sell or not:have bought, > pre,>next
*/
class Solution {
public:
int maxProfit(vector<int>& prices) {
auto sum=0,buy=0,sell=0;
auto len=prices.size();
auto cant_buy=false,cant_sell=false;
if(len<2) return -1;
for(auto i=0;i<len;i++)
{
// buy
if(!cant_buy && i<len-1 && prices[i]<prices[i+1] )
{
buy=prices[i];
// sum-=buy;
cant_buy=true;//can not buy
cant_sell=false;//can sell
printf("<=====buy:%d\n",buy);
}
//sell
if(!cant_sell && i<len-1 && prices[i]>prices[i+1] )
{
sell=prices[i];
sum-=buy;
sum+=sell;
cant_sell=true;//can not sell
cant_buy=false;//can buy
printf("=>sell:%d\n",sell);
}
printf("====price:%d\n",prices[i]);
}
return sum;
}
};
,,,,写的不对,,
/*
thinking:
1.get the smaller num to buy,
2.assume cur num to buy if next is smaller ,not buy,
3.when cur<before, cur<next buy,
================
for each num:
buy or not: not bought ,< pre,<next
sell or not:have bought, > pre,>next
*/
class Solution {
public:
int maxProfit(vector<int>& prices) {
auto sum=0,buy=0,sell=0;
auto len=prices.size();
auto have_buy=false,have_sell=true;
if(len<2) return -1;
buy=prices[0];
for(auto i=0;i<len;i++)
{
if( buy>prices[i])
{
buy=prices[i];
have_buy=true;
// // sell=prices[i];
// continue;
}
// have_buy=true;
printf("==>buy:%d\n",buy);
if( have_buy && sell< prices[i] )
{
sell=prices[i];
printf("sell:%d\n",sell);
// continue;
}
// have_sell=true;
if(sell_now)
{
sum+=sell-buy;
buy=prices[i+1];sell=prices[i+1];
}
printf("====price:%d\n",prices[i]);
}
return sum;
}
};
强迫症,浪费太多时间了。。。。
就是考虑不清楚,条件没写清。
枚举法呀。再来。
浪费时间:直接学习别人的吧。
class Solution {
public:
int maxProfit(vector<int>& prices) {
auto sum=0,buy=0,sell=0;
auto len=prices.size();
auto get_buy_p=false,get_sell_p=false;
if(len<2) return -1;
//find the reverse sort
if(prices[0]<prices[1])
buy=prices[0];
buy=prices[0];
for(auto i=0;i<len-1;i++)
{
if( prices[i] < prices[i+1])
{
buy=prices[i];
get_buy_p=true;
}
if(get_buy_p && prices[i] > prices[i+1] )
{
sell=prices[i];
get_sell_p=true;
printf("sell:%d\n",sell);
}
if(get_sell_p && get_buy_p)
{
sum+=sell-buy;
get_sell_p=false; get_buy_p=false;
// buy=prices[i+1];sell=prices[i+1];
}
printf("====price:%d\n",prices[i]);
}
return sum;
}
};
看懂大神的再写
果然是技巧啊,,,,厉害:
First we post the code here.
int maxProfit(vector<int> &prices) {
int ret = 0;
for (size_t p = 1; p < prices.size(); ++p)
ret += max(prices[p] - prices[p - 1], 0);
return ret;
}
Second, suppose the first sequence is "a <= b <= c <= d", the profit is "d - a = (b - a) + (c - b) + (d - c)" without a doubt. And suppose another one is "a <= b >= b' <= c <= d", the profit is not difficult to be figured out as "(b - a) + (d - b')". So you just target at monotone sequences.