问题描述
小明是一位股票交易员,他每天都会记录股票的价格。他发现,如果能够在价格最低时买入,在价格最高时卖出,就能获得最大利润。但是,他只能先买入再卖出,且最多只能完成一笔交易(即买入一次和卖出一次)。现在,他有一系列的历史价格记录,请你帮他计算出在这段时间内,他最多能获得多少利润。
要求:
- 设计一个算法,找出最大利润。如果无法获得利润(即价格一直下跌),则返回0。
- 时间复杂度应为 O(n),其中 n 是价格数组的长度。
- 尽量减少额外空间的使用,以体现你的算法优化能力。
测试样例
样例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;
}
运行结果
