zoukankan      html  css  js  c++  java
  • Best Time to Buy and Sell Stock

    Say you have an array for which the ith element is the price of a given stock on day i.

    If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

    Analyse: dp[i] = max(dp[i-1], prices[i] - lowest[0,..., i-1]).

    Runtime: 8ms.

     1 class Solution {
     2 public:
     3     int maxProfit(vector<int>& prices) {
     4         const int n = prices.size();
     5         if(n == 0) return 0;
     6         
     7         int dp[n] = {0};
     8         int lowest = prices[0];
     9         for(int i = 1; i < prices.size(); i++){
    10             dp[i] = max(dp[i - 1], prices[i] - lowest);
    11             lowest = min(lowest, prices[i]);
    12         }
    13         return dp[n - 1];
    14     }
    15 };

    or 

     1 class Solution {
     2 public:
     3     int maxProfit(vector<int>& prices) {
     4         if(prices.size() <= 1) return 0;
     5         
     6         int result = 0, pre = 0;
     7         int lowest = prices[0];
     8         for(int i = 1; i < prices.size(); i++){
     9             result = max(pre, prices[i] - lowest);
    10             lowest = min(lowest, prices[i]);
    11             pre = result;
    12         }
    13        return result;
    14     }
    15 };
  • 相关阅读:
    洛谷P4175 网络管理
    洛谷P2605 基站选址
    洛谷P3723 礼物
    bzoj3771 Triple
    洛谷P3321 序列统计
    bzoj2194 快速傅里叶之二
    1109课堂内容整理
    响应式网页
    表单隐藏域有什么作用?
    1106课堂笔记
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4743982.html
Copyright © 2011-2022 走看看