*leetcode #123 in cpp

来源:互联网 发布:淘宝在国外能用吗 编辑:程序博客网 时间:2024/06/06 00:00

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

Solution:

Since we can make at most 2 transactions, we can divide the array into two parts, each part contains a transaction. Then we get maximum profit from left part, and maximum profit from right part. Then we have total profit = left profit + right profit. We want to maximize the total profit, and thus we should try every left part [0....i], i = 0,...,n, calculate the total profit and get the maximum total profit. 

Code:

class Solution {public:    int maxProfit(vector<int>& prices) {        if(prices.empty()) return 0;        int n = prices.size();        vector<int> leftProfit(n,0); //leftProfit[i] = max profit we can get from day 0 to day i.         vector<int> rightProfit(n,0);//rightProfit[i] = max profit we can get from day i to day n        int profit = 0;        int cost = prices[0];                for(int i = 0; i < n; i ++){            if(prices[i] >= cost ){                profit = max(prices[i] - cost, profit);            }else{                cost = prices[i];            }            leftProfit[i] = profit;         }                profit = 0;        cost = prices[n-1];        for(int i = n-1; i >=0; i --){            if(prices[i] <= cost){                profit = max(cost - prices[i], profit);            }else{                cost = prices[i];            }            rightProfit[i] = profit;        }        profit = 0;        for(int i = 0; i < n; i ++){            profit = max(profit, leftProfit[i]+rightProfit[i]);        }        return profit;             }};


0 0
原创粉丝点击