当前位置:网站首页>剑指Offer 63.股票的最大利润
剑指Offer 63.股票的最大利润
2022-08-04 14:56:00 【HotRabbit.】
题目
假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?
示例 1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
示例 2:
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
限制:
0 <= 数组长度 <= 10^5
力扣(LeetCode)
链接:https://leetcode.cn/problems/gu-piao-de-zui-da-li-run-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
一次遍历:找到当前遍历过数组的最小值,并且将每个遍历的价格与最小值做差取最大值即为最大利润。
题解
class Solution {
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for (int i = 0;i < prices.length;i++){
if (prices[i] < minPrice) minPrice = prices[i];
else if (prices[i] - minPrice > maxProfit) maxProfit = prices[i] - minPrice;
}
return maxProfit;
}
}
边栏推荐
- G. Mountaineering Squad (violence & dfs)
- 【北亚数据恢复】IBM System Storage存储lvm信息丢失数据恢复方案
- 技术分享| 小程序实现音视频通话
- [机缘参悟-60]:《兵者,诡道也》-1-开篇:“死“与“生“都是天道
- 分布式链路追踪Jaeger + 微服务Pig在Rainbond上的实践分享
- Workaround without Project Facets
- vim common operation commands
- leetcode: 255 Verify preorder traversal sequence binary search tree
- 一看就会的Chromedriver(谷歌浏览器驱动)安装教程
- JCMsuite应用:倾斜平面波传播透过光阑的传输
猜你喜欢

Cisco - Small Network Topology (DNS, DHCP, Web Server, Wireless Router)

代码随想录笔记_动态规划_1049最后一块石头的重量II

特殊品种的二次开户验资金额

【HMS core】【Media】【视频编辑服务】 在线素材无法展示,一直Loading状态或是网络异常

快解析结合友加畅捷U+

Find My Technology | Prevent your pet from getting lost, Apple Find My technology can help you

【硬件架构的艺术】学习笔记(1)亚稳态的世界

【剑指offer33】二叉搜索树的后序遍历序列

郑轻新生校赛和中工选拔赛题解

1403. 非递增顺序的最小子序列
随机推荐
How to fall in love with a programmer
IP第十七天笔记
G. Mountaineering Squad (violence & dfs)
技术分享| 小程序实现音视频通话
RS|哨兵二号(.SAFE格式)转tif格式
X射线掠入射聚焦反射镜
一看就会的Chromedriver(谷歌浏览器驱动)安装教程
[Problem solving] QT update component appears "To continue this operation, at least one valid and enabled repository is required"
快解析结合友加畅捷U+
C# 局部函数与事件
数据库恢复
【Web技术】1401- 图解 Canvas 入门
[in-depth study of 4 g / 5 g / 6 g project - 50] : URLLC - 16 - the 3 GPP URLLC agreement, specification, technical principle of depth interpretation - 10 - high reliability technology - 1 - low codin
CF1527D MEX Tree(mex&树&容斥)
FRED Application: Capillary Electrophoresis System
AOSP内置APP特许权限白名单
leetcode: 251. Expanding 2D Vectors
Android Sqlite3 basic commands
广告电商系统开发功能只订单处理
Bluetooth Technology|In the first half of the year, 1.3 million charging piles were added nationwide, and Bluetooth charging piles will become the mainstream of the market