牛客题解 | 买卖股票的最好时机(一)
1.牛客题解 | N皇后问题2.牛客题解 | [CQOI2007]涂色PAINT3.牛客题解 | [NOIP2001]装箱问题4.牛客题解 | [NOIP2002 普及组] 过河卒5.牛客题解 | [ZJOI2010]COUNT 数字计数6.牛客题解 | abb7.牛客题解 | ranko的手表8.牛客题解 | 【模板】01背包9.牛客题解 | 【模板】二维前缀和10.牛客题解 | 【模板】二维差分11.牛客题解 | 【模板】前缀和12.牛客题解 | 【模板】单源最短路113.牛客题解 | 【模板】哈夫曼编码14.牛客题解 | 【模板】完全背包15.牛客题解 | 【模板】差分16.牛客题解 | 【模板】循环队列17.牛客题解 | 【模板】链表18.牛客题解 | 三角形最小路径和19.牛客题解 | 不相邻取数20.牛客题解 | 串21.牛客题解 | 乘积为正数的最长连续子数组
22.牛客题解 | 买卖股票的最好时机(一)
23.牛客题解 | 买卖股票的最好时机(三)24.牛客题解 | 买卖股票的最好时机(二)25.牛客题解 | 买卖股票的最好时机(四)26.牛客题解 | 二分查找-I27.牛客题解 | 二叉树中的最大路径和28.牛客题解 | 从中序与后序遍历序列构造二叉树29.牛客题解 | 信封嵌套30.牛客题解 | 兑换零钱31.牛客题解 | 分割等和子集32.牛客题解 | 删除相邻数字的最大分数33.牛客题解 | 删除链表的节点34.牛客题解 | 反转链表题目
解题思路
要求最大收益,我们需要找到最低的买入价格和在该买入价格之后的最高卖出价格。可以遍历一次数组:
- 用一个变量记录当前遍历过的最低价格
- 用另一个变量记录当前能获得的最大利润
- 对于每个价格,尝试更新最低价格,并计算当前价格卖出能获得的利润
代码
#include <iostream>
#include <vector>
using namespace std;
int maxProfit(vector<int>& prices) {
if(prices.empty()) return 0;
int minPrice = prices[0];
int maxProfit = 0;
for(int i = 1; i < prices.size(); i++) {
maxProfit = max(maxProfit, prices[i] - minPrice);
minPrice = min(minPrice, prices[i]);
}
return maxProfit;
}
int main() {
int n;
cin >> n;
vector<int> prices(n);
for(int i = 0; i < n; i++) {
cin >> prices[i];
}
cout << maxProfit(prices) << endl;
return 0;
}
import java.util.Scanner;
public class Main {
public static int maxProfit(int[] prices) {
if(prices.length == 0) return 0;
int minPrice = prices[0];
int maxProfit = 0;
for(int i = 1; i < prices.length; i++) {
maxProfit = Math.max(maxProfit, prices[i] - minPrice);
minPrice = Math.min(minPrice, prices[i]);
}
return maxProfit;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] prices = new int[n];
for(int i = 0; i < n; i++) {
prices[i] = sc.nextInt();
}
System.out.println(maxProfit(prices));
sc.close();
}
}
def max_profit(prices):
if not prices:
return 0
min_price = prices[0]
max_profit = 0
for price in prices[1:]:
max_profit = max(max_profit, price - min_price)
min_price = min(min_price, price)
return max_profit
n = int(input())
prices = list(map(int, input().split()))
print(max_profit(prices))
算法及复杂度
- 算法:动态规划(一次遍历)
- 时间复杂度:,其中 为数组长度
- 空间复杂度:,只使用了常数个变量
合集:
牛客笔试必刷101题单题解
分类:
牛客笔试必刷101题单题解
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现