LeetCode —— Best Time to Buy and Sell Stock III

来源:互联网 发布:广富宝网络借贷 编辑:程序博客网 时间:2024/06/14 22:48

链接:http://leetcode.com/onlinejudge#question_123

原题:

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

思路:简单的动态规划,因为限定最多只能有两次交易,而且交易不能重叠。那么分两步走好了,

由左向右记录一下到那一天为止最大的收益;同样,由右到左,记录最大收益。

然后加一加就可以了。


代码:

class Solution {public:    int maxProfit(vector<int> &prices) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int size = prices.size();        if (size <= 1)            return 0;                vector<int> leftIncomes(size, 0);        vector<int> rightIncomes(size, 0);                int min = prices[0];        for (int i=1; i<size; i++) {            if (prices[i] < min)                min = prices[i];            if (prices[i] - min > leftIncomes[i-1])                leftIncomes[i] = prices[i] - min;            else                leftIncomes[i] = leftIncomes[i-1];        }                int max = prices.back();        for (int i=size-2; i>=0; i--) {            if (prices[i] > max)                max = prices[i];            if (max - prices[i] > rightIncomes[i+1])                rightIncomes[i] = max - prices[i];            else                rightIncomes[i] = rightIncomes[i+1];        }                int profit = 0;        for (int i=0; i<size; i++) {            if (leftIncomes[i] + rightIncomes[i] > profit)                profit = leftIncomes[i] + rightIncomes[i];        }                return profit;    }};


原创粉丝点击