123 Best Time to Buy and Sell Stock III [Leetcode]

来源:互联网 发布:屏幕录制软件绿色版 编辑:程序博客网 时间:2024/05/19 17:51

题目内容:

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

解题思路:
解法一:
把股票价格拆分为两个部分,计算两个部分收益相加的最大值。
用两个数组分别保存前i天的最大收益asc[i]和后i天的最大收益desc[i].可以通过两次遍历求出。然后再遍历一遍,求前i天和后i+1天收益的最大值。

class Solution {public:    int maxProfit(vector<int>& prices) {        if(prices.size() == 0 || prices.size() == 1)return 0;        int min_price = prices[0];        int max_price = prices[prices.size() - 1];        int * profit_front = new int[prices.size()];        int * profit_back = new int[prices.size()];        profit_front[0] = 0;        profit_back[prices.size() - 1] = 0;        for(int i = 1; i < prices.size(); i++) {            //从前向后扫描,每次计算收益更新,并更新最小值            profit_front[i] = max(profit_front[i-1], prices[i] - min_price);            min_price = min(min_price, prices[i]);        }        for(int i = prices.size() - 2; i >= 0; i--) {            //从后向前扫描,每次计算收益更新,并更新最大值            profit_back[i] = max(profit_back[i + 1], max_price - prices[i]);            max_price = max(max_price, prices[i]);        }        int result = profit_front[prices.size() - 1];        for(int i = 0; i < prices.size() - 1; i++) {            result = max(result, profit_front[i] + profit_back[i + 1]);        }        return result;    }};

另一种写法:
写起来更繁琐一些,注意判断条件

class Solution {public:    int maxProfit(vector<int>& prices) {        int size(prices.size()), result(0);        if(size <= 1)            return 0;        int min(prices[0]), max(prices[0]);        vector<int> asc(size, 0), desc(size, 0);        for(int i = 1; i < size; ++i) {            asc[i] = asc[i-1];            if(prices[i] < min) {                min = prices[i];                max = INT_MIN;            }            else if(prices[i] > max) {                max = prices[i];                int temp(max - min);                asc[i] = asc[i-1] > temp ? asc[i-1] : temp;            }        }        desc[0] = asc[size - 1];        min = prices[size - 1];        max = prices[size - 1];        for(int i = size - 2; i > 0; --i) {            desc[i] = desc[i+1];            if(prices[i] > max) {                max = prices[i];                min = INT_MAX;            }            else if(prices[i] < min) {                min = prices[i];                int temp(max - min);                desc[i] = desc[i+1] > temp ? desc[i+1] : temp;            }        }        result = desc[0];        for(int i = 0; i < size - 1; ++i) {            int temp(asc[i] + desc[i + 1]);            result = result > temp ? result : temp;        }        return result;    }};

解法二:
通用解法,参见Best Time to Buy and Sell Stock IV.

0 0