leetCode:121\122\309 股票买入和卖出获取最大收益问题

来源:互联网 发布:javascript 显示隐藏 编辑:程序博客网 时间:2024/04/30 20:34
/**leetCode 121 :动态规划求 最佳买入和卖出股票    给出一组int数组,每个值代表当天股票的价格,你只能买1次并且卖1次,求最大收益    动态规划求解:*/int maxProfit(vector<int>& prices) {    if(prices.size()==0)        return 0;    int buy = INT_MAX;    int profit = 0;    for(int i=0;i<prices.size();i++){        buy = min(buy,prices[i]);        profit = max(profit,prices[i]-buy);    }    return profit;}


/**leetCode 122 :动态规划求 最佳买入和卖出股票    给出一组int数组,每个值代表当天股票的价格,你可以买入多次并卖出多次,但是买入之前必须先卖出,求最大收益    动态规划求解:*/int maxProfit(vector<int>& prices) {    if(prices.size()==0)        return 0;    int buy = INT_MAX;    int profit = 0;    int sum = 0;    for(int i=0;i<prices.size();i++){        if(buy>=prices[i]){            buy = prices[i];            sum+=profit;            profit=0;        }        if(profit<prices[i]-buy){            profit = prices[i]-buy;        }        else{            sum+=profit;            profit=0;            buy = prices[i];        }    }    sum+=profit;    return sum;}
/**leetCode 309:与上面一样,仍然计算股票的最大收益,可以完成多次交易,但是必须在买这个股票之前先卖掉它,在你卖掉股票之后的一天是不能买股票的。交易有三个状态,buy,sell,rest;定义buy[i]是前i天的任意序列以buy结尾的获取的最大利润    sell[i]是前i天的任意序列以sell结尾的获取的最大利润    rest[i]是前i天的任意序列以rest结尾的获取的最大利润    则buy[i] = max(rest[i-1]-prices[i],buy[i-1]);      sell[i] = max(buy[i-1]+prices[i],sell[i-1]);      rest[i] = max(buy[i-1],sell[i-1],rest[i-1]);    又因为 buy[i]<=rest[i],           rest[i]<=sell[i];    所以 rest[i] = sell[i-1];    带入最先定义的3个公式:    buy[i] = max(sell[i-2]-prices[i],buy[i-1]);    sell[i] =max(buy[i-1]+prices[i],sell[i-1]);*/int maxProfit2(vector<int>& prices) {   int prebuy =0;   int presell = 0;   int buy =INT_MIN;   int sell=0;   for(int price:prices){        prebuy = buy;        buy = max(presell-price,prebuy);        presell = sell;        sell = max(prebuy+price,presell);        cout<<prebuy<<" "<<sell<<endl;   }    return sell;}



0 0
原创粉丝点击