zoukankan      html  css  js  c++  java
  • 剑指 Offer 63. 股票的最大利润

    思路

    方法一:暴力法

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

    方法二:动态规划

     1 class Solution {
     2 public:
     3     int maxProfit(vector<int>& prices) {
     4         if(prices.size() < 2)    //这种情况无法交易
     5             return 0;
     6             
     7         vector<int> dp(prices.size(), 0);
     8         int minPrice = prices[0];
     9         dp[0] = 0;
    10 
    11         for(int i = 1; i < prices.size(); ++i) {
    12             if(prices[i] < minPrice)
    13                 minPrice = prices[i];
    14             
    15             dp[i] = max(dp[i-1], prices[i] - minPrice);
    16         }
    17 
    18         return dp[prices.size()-1];
    19     }
    20 }

    复杂度分析

    时间复杂度:O(n)

    空间复杂度:O(n)

    空间优化

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

    复杂度分析

    时间复杂度:O(n)

    空间复杂度:O(1)

  • 相关阅读:
    spring三大框架整合
    spring基础内容
    安装Apache报80端口被占用 pid 4
    Bugzilla说明
    管理员权限的用户
    mac怎么连接windows远程桌面
    java化测试神器-流量回放平台
    PyAutoGUI——图形用户界面自动化
    (Python OpenGL)【5】平移 PyOpenGL
    (Python OpenGL)【4】Uniform变量 PyOpenGL
  • 原文地址:https://www.cnblogs.com/FengZeng666/p/13977880.html
Copyright © 2011-2022 走看看