当前位置:网站首页>剑指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;
}
}
边栏推荐
猜你喜欢
随机推荐
QT笔记——Q_INVOKABLE了解
[Opportunity Enlightenment-60]: "Soldiers, Stupid Ways"-1- Opening: "Death" and "Life" are the way of heaven
宣传海报
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
【Today in History】August 4: First female Turing Award winner; NVIDIA acquires MediaQ; first Cybersecurity Challenge completed
苏秋贵:揭秘绿联科技用5年时间从0做到6亿,如何一枝独秀?
7 天找个 Go 工作,Gopher 要学的条件语句,循环语句 ,第3篇
Leetcode: 215 disorderly to find the first big k element in the array
Makefile syntax and usage notes
谷歌插件.crx文件下载后被自动删除的解决方法
vim 常用操作命令
leetcode:241. 为运算表达式设计优先级
【Web技术】1401- 图解 Canvas 入门
兆骑科创创新创业大赛活动举办,线上直播路演,投融资对接
C# 判断文件编码
[Beiya data recovery] IBM System Storage storage lvm information lost data recovery solution
Oracle database user creation, restart, import and export
微软表示将向内部网络安全专家共享数据 为企业提供更安全保护
Resharper 如何把类里的类移动到其他文件
华为云 & 达达,帮有情人“一键送达”









