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

Note: 
      You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).算法

 

翻譯:假設你有一個數組,其中第i 個元素是第i天給定股票的價格。設計一個算法來找到最大的利潤。您最多能夠完成兩個交易。數組

注意: 您不得同時從事多個交易(即,您必須在再次購買以前出售股票)。spa

 

#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;
}
本站公眾號
   歡迎關注本站公眾號,獲取更多信息