zoukankan      html  css  js  c++  java
  • 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;
    }
    既然选择了远方,便只顾风雨兼程
  • 相关阅读:
    概述反射和序列化
    读书笔记6pandas简单使用
    读书笔记5基于matplotlib画图
    读书笔记4数据的读入和保存
    读书笔记3数组的一些常用函数
    introduction to python for statistics,analysis笔记3
    introduction to python for statistics,analysis笔记2
    introduction to anaconda
    图像的线性空间滤波matlab实现
    C-I/O操作函数详解
  • 原文地址:https://www.cnblogs.com/Forever-Road/p/6978078.html
Copyright © 2011-2022 走看看