zoukankan      html  css  js  c++  java
  • [LeetCode] Best Time to Buy and Sell Stock III

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

     1 class Solution {
     2 public:
     3     int maxProfit(vector<int> &prices) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         if (prices.size() == 0)
     7             return 0;
     8             
     9         vector<int> f1(prices.size());
    10         vector<int> f2(prices.size());
    11         
    12         int minV = prices[0];
    13         f1[0] = 0;
    14         for(int i = 1; i < prices.size(); i++)
    15         {
    16             minV = min(minV, prices[i]);
    17             f1[i] = max(f1[i-1], prices[i] - minV);
    18         }
    19         
    20         int maxV = prices[prices.size()-1];
    21         f2[f2.size()-1] = 0;
    22         for(int i = prices.size() - 2; i >= 0; i--)
    23         {
    24             maxV = max(prices[i], maxV);
    25             f2[i] = max(f2[i+1], maxV - prices[i]);
    26         }
    27         
    28         int sum = 0;
    29         for(int i = 0; i < prices.size(); i++)
    30             sum = max(sum, f1[i] + f2[i]);
    31             
    32         return sum;
    33     }
    34 };
  • 相关阅读:
    CentOS/Ubuntu安装最新的gcc-9
    CentOS 7 源码安装 CMake 3.16.2 最新稳定版。解决 cmake: command not found 问题
    堆排序
    linux可重入、异步信号安全和线程安全
    目录
    教程文档
    推荐文章
    学习文档
    开发工具-索引
    同步/异步/阻塞/非阻塞
  • 原文地址:https://www.cnblogs.com/chkkch/p/2795178.html
Copyright © 2011-2022 走看看