当前位置:网站首页>2022.04.23(LC_714_买卖股票的最佳时机含手续费)
2022.04.23(LC_714_买卖股票的最佳时机含手续费)
2022-04-23 18:51:00 【Leeli9316】
方法:贪心
class Solution {
public int maxProfit(int[] prices, int fee) {
int profit = 0;
//buy表示在最大化收益的前提下,拥有一支股票的最低买入价格
int buy = prices[0] + fee;
for (int i = 1; i < prices.length; i++) {
//如果当前的股票价格加上手续费小于buy
//说明可以以更低的价格买入,更新buy
if (prices[i] + fee < buy) {
buy = prices[i] + fee;
//如果当前的股票价格大于buy,可以获得收益
//但实际上,此时卖出股票可能并不是全局最优的(例如下一天股票价格继续上升)
} else if (prices[i] > buy) {
profit += prices[i] - buy;
//所以将buy更新为prices[i],如果下一天股票价格继续上升,
//会获得prices[i+1]−prices[i]的收益,加上这一天prices[i]−buy 的收益,
//恰好就等于在这一天不进行任何操作,而在下一天卖出股票的收益
buy = prices[i];
}
}
return profit;
}
}
版权声明
本文为[Leeli9316]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Leeli9316/article/details/124361451
边栏推荐
- Domestic GD chip can filter
- mysql_linux版本的下載及安裝詳解
- After opening the original normal project, the dependency package displays red and does not exist.
- Click the input box to pop up the keyboard layout and move up
- 22 year flying Book manpower Kit
- ESP32 LVGL8. 1 - anim animation (anim 16)
- Actual combat of Nacos as service configuration center
- Teach you to quickly rename folder names in a few simple steps
- Recyclerview control list item layout match_ Fundamental principle of parent attribute invalidation
- Introduction to QT programming
猜你喜欢
ctfshow-web362(SSTI)
Chondroitin sulfate in vitreous
[popular science] CRC verification (I) what is CRC verification?
使用晨曦记账本,分析某个时间段每个账户收支结余
解决:cnpm : 无法加载文件 ...\cnpm.ps1,因为在此系统上禁止运行脚本
ESP32 LVGL8. 1 - img picture (IMG 20)
Esp32 (UART 485 communication) - 485 communication of serial port (3)
从技术体系到商业洞察,中小研发团队架构实践之收尾篇
ESP32 LVGL8. 1 - msgbox message box (msgbox 28)
ESP32 LVGL8. 1 - label (style 14)
随机推荐
MVVM模型
ESP32 LVGL8. 1 - textarea text area (textarea 26)
After opening the original normal project, the dependency package displays red and does not exist.
Advanced transfer learning
mysql_linux版本的下載及安裝詳解
关于unity文件读取的操作(一)
简化路径(力扣71)
Use of kotlin collaboration in the project
玻璃体中的硫酸软骨素
Dynamically add and delete layouts
[mathematical modeling] - analytic hierarchy process (AHP)
Tencent map and high logo removal method
Ucosiii transplantation and use, reference punctual atom
ESP32 LVGL8. 1 - arc (arc 19)
迁移学习进阶
ctfshow-web362(SSTI)
Excel intercept text
Nacos作为服务配置中心实战
ESP32 LVGL8. 1 - BTN button (BTN 15)
Treatment of incomplete display of listview height