【C++】每日一题 121 买卖股票的最佳时机

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。

#include <vector>
#include <algorithm>

using namespace std;

int maxProfit(vector<int>& prices) {
    int n = prices.size();
    if (n <= 1) return 0;

    int maxProfit = 0;
    int minPrice = prices[0];

    for (int i = 1; i < n; ++i) {
        maxProfit = max(maxProfit, prices[i] - minPrice);
        minPrice = min(minPrice, prices[i]);
    }

    return maxProfit;
}

int main() {
    vector<int> prices = {7, 1, 5, 3, 6, 4};
    int max_profit = maxProfit(prices);
    cout << "Maximum profit: " << max_profit << endl;
    return 0;
}

时间复杂度分析:
遍历数组一次,时间复杂度为 O(n),其中 n 为数组的长度。
空间复杂度分析:
仅使用了常量级别的额外空间,空间复杂度为 O(1)。
该算法的核心思想是维护两个变量:当前最小价格(minPrice)和当前最大利润(maxProfit)。在遍历数组时,更新最小价格和计算当前价格与最小价格的差值,得到当前最大利润。最终返回最大利润即可。

相关推荐

  1. C++】每日 121 买卖股票最佳时机

    2024-04-06 04:14:05       36 阅读
  2. LeetCode-热100:121. 买卖股票最佳时机

    2024-04-06 04:14:05       45 阅读
  3. 121. 买卖股票最佳时机

    2024-04-06 04:14:05       56 阅读
  4. 121. 买卖股票最佳时机(简单)

    2024-04-06 04:14:05       57 阅读
  5. 121_买卖股票最佳时机

    2024-04-06 04:14:05       48 阅读
  6. leetcode121. 买卖股票最佳时机

    2024-04-06 04:14:05       55 阅读
  7. Leetcode 121 买卖股票最佳时机

    2024-04-06 04:14:05       59 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-06 04:14:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-06 04:14:05       101 阅读
  3. 在Django里面运行非项目文件

    2024-04-06 04:14:05       82 阅读
  4. Python语言-面向对象

    2024-04-06 04:14:05       91 阅读

热门阅读

  1. 面试算法-142-找到字符串中所有字母异位词

    2024-04-06 04:14:05       35 阅读
  2. TS学习02 面向对象 类、封装继承、接口、泛型

    2024-04-06 04:14:05       32 阅读
  3. 小组分享内容二:Jsoup部分(未完待续)

    2024-04-06 04:14:05       34 阅读
  4. MYSQL-----多表查询详解,配有练习讲解

    2024-04-06 04:14:05       37 阅读
  5. Django --静态文件

    2024-04-06 04:14:05       32 阅读
  6. ubunu18.04源码安装opencv 4.8.0

    2024-04-06 04:14:05       38 阅读