Leetcode_best-time-to-buy-and-sell-stock-iii

设计算法寻找最大利润,限制最多完成两次交易。首先顺序遍历记录当前为止一次交易的最大利润和最小价格,然后逆序遍历记录从最后开始的最后一次交易的最大利润。如果在某个点有重复,即之前的最大利润的终点和之后的最大利润的起点是同一点,那就是一次交易;否则为两次交易。最终返回最大利润。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

地址:http://oj.leetcode.com/problems/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).

思路:1. 顺序遍历记录当前为止一次可以获取的最大利润,记录并更新从头开始的最小值。

           2. 逆序遍历记录当前开始到最后一次可以获取的最大利润,记录并更新从尾开始的最大值。

            如果在某个点有重复,即之前获得的最大值的终点和之后获得的最大值的起点是同一点,其实就是一次交易。比如 3 1 2 7 10, 顺序遍历会记录3->7,逆序会记录7->10,如果在这个点有最大值,其实就是一次交易。如果不发生在实际的同一点(注意当前交易所得并不一定是最大,可能会被之前更大的值更新),那就是两次交易和。

参考代码:80ms

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.size()<=1)
            return 0;
        int buy_low = INT_MAX, sell_high = INT_MIN, profit = 0, ans = 0;
        vector<int>first_profit(prices.size(), 0);
        for(int i = 0; i<prices.size(); ++i)
        {
            if(prices[i]<buy_low)
                buy_low = prices[i];
            else
                profit = max(profit, prices[i]-buy_low);
            first_profit[i] = profit;
        }
        profit = 0;
        for(int i = prices.size()-1; i>=0; --i)
        {
            if(prices[i]>sell_high)
                sell_high = prices[i];
            else
                profit = max(profit, sell_high - prices[i]);
            ans = max(ans, first_profit[i] + profit);
        }
        return ans;
    }
};


 
//SECOND TRIAL, 60ms
class Solution {
public :
     int maxProfit ( vector < int > & prices ) {
         if ( prices . size () <= 1 )
             return 0 ;
         vector < int > v1 ( prices . size (), 0 ), v2 ( prices . size (), 0 );
         int low = prices [ 0 ], high = prices [ prices . size () - 1 ];
         for ( int i = 1 ; i < prices . size (); ++ i )
         {
             low = min ( low , prices [ i ]);
             v1 [ i ] = max ( v1 [ i - 1 ], prices [ i ] - low );
         }
            
         for ( int j = prices . size () - 2 ; j >= 0 ; -- j )
         {
             high = max ( high , prices [ j ]);
             v2 [ j ] = max ( v2 [ j + 1 ], high - prices [ j ]);
         }
         int ans = 0 ;
         for ( int i = 0 ; i < prices . size (); ++ i )
             ans = max ( ans , v1 [ i ] + v2 [ i ]);
         return ans ;
     }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值