zoukankan      html  css  js  c++  java
  • leetcode 123. Best Time to Buy and Sell Stock III

    传送门

    123. Best Time to Buy and Sell Stock III

     
     My Submissions
     
    • Total Accepted: 62311
    • Total Submissions: 230292
    • Difficulty: Hard

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

    Subscribe to see which companies asked this question

    Show Similar Problems
     
    思路:
    思想来源于动态规划,如果以arr[i]为第二个投资点,那么,必须找到i-1前面的最大投资收益
    so,,,左右各dp一次。。。
     
     1 class Solution {
     2 public:
     3     int maxProfit(vector<int>& prices) {
     4         int sz = prices.size();
     5         vector<int> left(sz + 1,0);
     6         int i;
     7         int mi = INT_MAX;
     8         for(i = 0;i < sz;i++){
     9             if(i != 0){
    10                 left[i] = left[i - 1];
    11             }
    12             if(prices[i] < mi){
    13                 mi = prices[i];
    14             }
    15             else{
    16                 left[i] = max(left[i],prices[i] - mi);
    17             }
    18         }
    19         
    20         vector<int> right(sz + 1,0);
    21         int ma = INT_MIN;
    22         for(i = sz - 1;i >= 0;i--){
    23             if(i != sz - 1){
    24                 right[i] = right[i + 1];
    25             }
    26             if(prices[i] > ma){
    27                 ma = prices[i];
    28             }
    29             else{
    30                 right[i] = max(right[i],ma - prices[i]);
    31             }
    32         }
    33         //for(i = 0;i < sz;i++){
    34         //    printf(" i = %d left = %d right = %d
    ",i,left[i],right[i]);
    35         //}
    36         
    37         int ma_profile = left[sz - 1];
    38         for(i = 0;i < sz - 1;i++){
    39             ma_profile = max(ma_profile,left[i] + right[i + 1]);
    40         }
    41         return ma_profile;
    42     }
    43 };
  • 相关阅读:
    插件集合
    postgis_LayerTransform
    react-高阶组件
    react-自定义事件
    Immutable 详解及 React 中实践
    babel-preset-env: a preset that configures Babel for you
    彻底解决Webpack打包慢的问题
    打包图片
    drag
    brush
  • 原文地址:https://www.cnblogs.com/njczy2010/p/5703761.html
Copyright © 2011-2022 走看看