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

Posted Forever-Road

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}

 

以上是关于best-time-to-buy-and-sell-stock的主要内容,如果未能解决你的问题,请参考以下文章

JS基础之pageX/Y ,clientX/Y,screenX/Y,offsetX/Y区别

设X,Y是连续型随机变量,证明:若X与Y独立,则X^2与Y^2相互独立

三个正数 x、y、z 的组合,使得 x + y、x - y、y + z、y - z、x + z 和 x - z 是完全平方

原生js获取鼠标坐标方法全面讲解:clientX/Y,pageX/Y,offsetX/Y,layerX/Y,screenX/Y

X与Y独立吗?

已知方程xy=e^(x+y),求一阶导数y'