best-time-to-buy-and-sell-stock

  Say you have an array for which the i th 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 个元素是第i天给定股票的价格。设计一个算法来找到最大的利润。您最多可以完成两个交易。

注意: 您不得同时从事多个交易(即,您必须在再次购买之前出售股票)。

 

#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdlib.h>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:

    int maxProfit(vector<int> &prices)
    {
        if (prices.size() < 2)
        {
            return 0;
        }
        //假设为穷光蛋,以下变量都表示现有资金
        int first_buy = INT_MIN;
        int first_sell = 0;
        int second_buy = INT_MIN;
        int second_sell = 0;

        for (int i = 0; i < prices.size(); i++)
        {
            //第一次是否买股票,当股票价格低于现有价格(first_buy)则买,否则不买
            first_buy = max(first_buy, -prices[i]);
            //第一次是否卖股票,当股票价格高于现有价格(first_sell)则卖,否则不卖
            first_sell = max(first_sell, prices[i] + first_buy);
            //第二次是否买股票
            second_buy = max(second_buy, first_sell - prices[i]);
            //第二次是否卖股票
            second_sell = max(second_sell, second_buy + prices[i]);
        }
        return second_sell;
    }
};
int main()
{
    vector<int> result = {3,8,2,5,3,9};
    Solution so;
    cout << so.maxProfit(result) <<endl;
    return 0;
}

 

posted @ 2017-06-10 10:47  Forever-Road  阅读(136)  评论(0编辑  收藏  举报