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;
}

运行结果

相关推荐
Logic1011 小时前
C语言/数据结构位运算题解:异或XOR找出货币交易中的“独特面值“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
ctlover1 小时前
数据结构:树
数据结构·python
景熙55233 小时前
14.Java 集合框架从入门到源码万字详解(含 ArrayList/LinkedList/HashMap 源码、泛型通配符、红黑树)
java·开发语言·数据结构·算法
aaaameliaaa3 小时前
结构体 结构体
c语言·笔记·算法
是隼人4 小时前
buuctf-pwn PWN8题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
SendTomo4 小时前
.ico透明图标在线生成下载平台深度解析
大数据·数据结构·数据库·数据仓库·个人开发
GG-_-Bond4 小时前
9.1kv存储持久化模拟面试
linux·c语言·数据结构·c++
程序员阿鹏4 小时前
双亲委派机制
java·jvm·数据结构·后端
runningshark5 小时前
数据结构-第二章-线性表及其顺序存储
数据结构