码迷,mamicode.com
首页 > 其他好文 > 详细

123. Best Time to Buy and Sell Stock III

时间:2018-01-04 18:17:28      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:int   star   git   discuss   min   post   algo   max   log   

欢迎fork and star:Nowcoder-Repository-github

123. 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).

解析

//Buy and Sell Stock iii
class Solution_123 {
public:
    int maxProfit(vector<int> &prices) {

        //1.买一次相当于减一个数,
        //2.买卖两次维持当前最大的收益

        int buy1 = INT_MIN, sell1 = 0;
        int buy2 = INT_MIN, sell2 = 0;

        for (int i = 0; i < prices.size();i++)
        {
            buy1 = max(buy1, -prices[i]);
            sell1 = max(sell1, buy1 + prices[i]); //一次买卖现有的收益

            buy2 = max(buy2, sell1 - prices[i]); //又要使用一些钱
            sell2 = max(sell2, buy2 + prices[i]);
        }
        return sell2;
    }
};

123. Best Time to Buy and Sell Stock III

标签:int   star   git   discuss   min   post   algo   max   log   

原文地址:https://www.cnblogs.com/ranjiewen/p/8194166.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!