zoukankan      html  css  js  c++  java
  • 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).

    Solution: dp. max profit = max { l2r[0...i] + r2l[i+1...N-1] }. 0 <= i <= N-1

     1 class Solution {
     2 public:
     3     // max_profit = max {l2r[0,1,...,i], r2l[i+1,...,N-1]}
     4     int maxProfit(vector<int> &prices) {
     5         if (prices.size() <= 1) {
     6             return 0;
     7         }
     8         int N = prices.size();
     9         vector<int> l2r(N,0);
    10         vector<int> r2l(N,0);
    11         
    12         int minv = prices[0];
    13         for(int i = 1; i < N; i++) {
    14             minv = min(minv, prices[i]);
    15             l2r[i] = max(l2r[i-1], prices[i]-minv);
    16         }
    17         
    18         int maxv = prices[N-1];
    19         for(int i = N-2; i >= 0; i--) {
    20             maxv = max(maxv, prices[i]);
    21             r2l[i] = max(r2l[i+1], maxv-prices[i]);
    22         }
    23         
    24         int res = l2r[N-1];
    25         for(int i = 0; i < N-1; i++) {
    26             res = max(res, l2r[i]+r2l[i+1]);
    27         }
    28         return res;
    29     }
    30 };
  • 相关阅读:
    IOS Xcode编译项目-报错“ld: library not found for -XX”
    ios中关键词weak,assign,copy.strong等的区别
    iOS 控件
    iOS图片处理
    iOS 音频
    C语言文件操作
    iOS 删除相册中照片--来自简书
    ios sourecTree
    ios音频处理
    编码格式简介
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3646396.html
Copyright © 2011-2022 走看看