C语言/数据结构贪心算法题解:买卖股票的最佳时机——一次交易最大利润(O(n)时间O(1)空间)

问题描述

小明是一位股票交易员,他每天都会记录股票的价格。他发现,如果能够在价格最低时买入,在价格最高时卖出,就能获得最大利润。但是,他只能先买入再卖出,且最多只能完成一笔交易(即买入一次和卖出一次)。现在,他有一系列的历史价格记录,请你帮他计算出在这段时间内,他最多能获得多少利润。

要求:

  1. 设计一个算法,找出最大利润。如果无法获得利润(即价格一直下跌),则返回0。
  2. 时间复杂度应为 O(n),其中 n 是价格数组的长度。
  3. 尽量减少额外空间的使用,以体现你的算法优化能力。

测试样例

样例1:

输入:prices = [7, 1, 5, 3, 6, 4] 输出:5 解释:在第2天(价格=1)买入,在第5天(价格=6)卖出,利润为6-1=5。注意不能在价格7时买入,因为之后卖出需要价格更高,但无法实现。

样例2:

输入:prices = [7, 6, 4, 3, 1] 输出:0 解释:在这种情况下,价格一直下跌,无法完成交易(即无法获得利润),所以返回0。

样例3:

输入:prices = [3, 2, 6, 5, 0, 3] 输出:4 解释:在第2天(价格=2)买入,在第3天(价格=6)卖出,利润为6-2=4。注意不能在价格0时买入,因为之后卖出(价格3)的利润为3,但小于4。

约束条件

  • 1 ≤ prices.length ≤ 10^5
  • 0 ≤ pricesi ≤ 10^4
  • 只能进行一次买入和卖出操作
  • 买入必须在卖出之前

程序代码

#include <stdio.h>

int maxProfit(int* prices, int pricesSize) {

if (pricesSize <= 1) return 0;

int minPrice = prices0;

int maxProfit = 0;

for (int i = 1; i < pricesSize; i++) {

if (pricesi < minPrice) {

minPrice = pricesi;

} else {

int profit = pricesi - minPrice;

if (profit > maxProfit) {

maxProfit = profit;

}

}

}

return maxProfit;

}

int main() {

int prices1\[\] = {7, 1, 5, 3, 6, 4};

int prices2\[\] = {7, 6, 4, 3, 1};

int prices3\[\] = {3, 2, 6, 5, 0, 3};

printf("%d\n", maxProfit(prices1, 6)); // 5

printf("%d\n", maxProfit(prices2, 5)); // 0

printf("%d\n", maxProfit(prices3, 6)); // 4

return 0;

}

cpp 复制代码
#include <stdio.h>

int maxProfit(int* prices, int pricesSize) {
    if (pricesSize <= 1) return 0;
    
    int minPrice = prices[0];
    int maxProfit = 0;
    
    for (int i = 1; i < pricesSize; i++) {
        if (prices[i] < minPrice) {
            minPrice = prices[i];
        } else {
            int profit = prices[i] - minPrice;
            if (profit > maxProfit) {
                maxProfit = profit;
            }
        }
    }
    
    return maxProfit;
}

int main() {
    int prices1[] = {7, 1, 5, 3, 6, 4};
    int prices2[] = {7, 6, 4, 3, 1};
    int prices3[] = {3, 2, 6, 5, 0, 3};
    
    printf("%d\n", maxProfit(prices1, 6));  // 5
    printf("%d\n", maxProfit(prices2, 5));  // 0
    printf("%d\n", maxProfit(prices3, 6));  // 4
    
    return 0;
}

运行结果

相关推荐
Ada's5 小时前
【计算机基础系列】003:Python数据结构
开发语言·数据结构·python
wanderist.8 小时前
线性筛法详解:从筛质数到欧拉函数、Möbius 函数与约数函数
java·数据结构·算法
All for pursuit.9 小时前
【设计-1】208.实现Trie (前缀树)
数据结构·c++·算法·leetcode
Escalating_xu10 小时前
【C 语言】深入理解指针(5):sizeof、strlen、数组名语义与指针笔试题全解析
java·c语言·开发语言
Code_Solitude10 小时前
c语言:递归
java·c语言·算法
程序员清风10 小时前
哈希表:从键值映射到高效查找
数据结构·哈希算法·散列表
万年咸鱼10 小时前
解决C语言的内存释放机制
java·c语言·python
老王爱玩车12 小时前
自定义类型:结构体
c语言·开发语言·学习
Logic10113 小时前
C语言/数据结构字符串题解:最短循环节——找出能重复构成原串的最短基础子串
c语言·数据结构·字符串·枚举·时间复杂度·算法题·kmp优化
我就是不信14 小时前
CuTest:轻量级 C 语言单元测试框架实战指南
c语言·单元测试·log4j