当前位置:网站首页>121. 买卖股票的最佳时机
121. 买卖股票的最佳时机
2022-07-07 13:49:00 【zzu菜】
121. 买卖股票的最佳时机
给定一个数组 prices
,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
示例 1:
输入:[7,1,5,3,6,4]
输出:5
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
示例 2:
输入:prices = [7,6,4,3,1]
输出:0
解释:在这种情况下, 没有交易完成, 所以最大利润为 0。
提示:
1 <= prices.length <= 105
0 <= prices[i] <= 104
思考
首先我们假设第一天卖出股票,即当前卖出股票的价格为sellPrice
如果之后第i天的股票价格比卖出的股票价格低 sellPrice = prices[i]
否则 max = Math.max(max,prices[i]-sellPrice);
public int maxProfit(int[] prices) {
int sellPrice = prices[0];
int max = Integer.MIN_VALUE;
for (int i=1;i<prices.length;i++){
if(prices[i]<sellPrice){
sellPrice = prices[i];
}else {
max = Math.max(max,prices[i]-sellPrice);
}
}
if (max<0) return 0;
return max;
}
边栏推荐
- 10 schemes to ensure interface data security
- Function: JS Click to copy content function
- SysOM 案例解析:消失的内存都去哪了 !| 龙蜥技术
- Unity3D_ Class fishing project, control the distance between collision walls to adapt to different models
- 【花雕体验】15 尝试搭建Beetle ESP32 C3之Arduino开发环境
- Mesh merging under ue4/ue5 runtime
- Three. Introduction to JS learning notes 17: mouse control of 3D model rotation of JSON file
- Yunxiaoduo software internal test distribution test platform description document
- Getting started with webgl (3)
- AB package details in unity (super detail, features, packaging, loading, manager)
猜你喜欢
分步式监控平台zabbix
山东老博会,2022中国智慧养老展会,智能化养老、适老科技展
Strengthen real-time data management, and the British software helps the security construction of the medical insurance platform
numpy--疫情数据分析案例
The download button and debug button in keil are grayed out
LeetCode2_ Add two numbers
Use of SVN
过度依赖补助,大客户收款难,冲刺“国产数据库第一股”的达梦后劲有多足?
Three. JS introductory learning notes 18: how to export JSON files with Blender
Create lib Library in keil and use lib Library
随机推荐
How to build your own super signature system (yunxiaoduo)?
Particle effect for ugui
Webgl texture
招标公告:福建省农村信用社联合社数据库审计系统采购项目(重新招标)
Numpy -- data cleaning
numpy---基础学习笔记
Cut ffmpeg as needed, and use emscripten to compile and run
航运船公司人工智能AI产品成熟化标准化规模应用,全球港航人工智能/集装箱人工智能领军者CIMC中集飞瞳,打造国际航运智能化标杆
A JS script can be directly put into the browser to perform operations
[excelexport], Excel to Lua, JSON, XML development tool
Do not use memset to clear floating-point numbers
AE learning 01: AE complete project summary
Three. JS introductory learning notes 15: threejs frame animation module
Cocos creator collision and collision callback do not take effect
Limit of total fields [1000] in index has been exceeded
Syntaxhighlight highlights the right scroll bar
一个普通人除了去工厂上班赚钱,还能干什么工作?
After UE4 is packaged, mesh has no material problem
Spin animation of Cocos performance optimization
20th anniversary of agile: a failed uprising