当前位置:网站首页>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
边栏推荐
- Setting up keil environment of GD single chip microcomputer
- K210 serial communication
- Database computer experiment 4 (data integrity and stored procedure)
- Implementation of TCP UDP communication with golang language
- Summary of actual business optimization scheme - main directory - continuous update
- Domestic GD chip can filter
- ESP32 LVGL8. 1 - msgbox message box (msgbox 28)
- Seata处理分布式事务
- Chondroitin sulfate in vitreous
- Loop path
猜你喜欢
ctfshow-web362(SSTI)
Use bitnami / PostgreSQL repmgr image to quickly set up PostgreSQL ha
微搭低代码零基础入门课(第三课)
12个例子夯实promise基础
【科普】CRC校验(一)什么是CRC校验?
c#:泛型反射
On iptables
Halo open source project learning (VII): caching mechanism
Use Chenxi bookkeeping book to analyze the balance of revenue and expenditure of each account in a certain period of time
Eight bit binary multiplier VHDL
随机推荐
WebView opens H5 video and displays gray background or black triangle button. Problem solved
K210串口通信
12个例子夯实promise基础
Dynamically add and delete layouts
ESP32 LVGL8. 1. Detailed migration tutorial of m5stack + lvgl + IDF (27)
PyGame tank battle
根据快递单号查询物流查询更新量
迁移学习进阶
Esp32 (UART ecoh) - serial port echo worm learning (2)
mysql_linux版本的下载及安装详解
Ionic instruction set order from creation to packaging
Methods of nested recycleview to solve sliding conflict and incomplete item display
特征选择feature_selection--SelectKBest
The corresponding permissions required to automatically open the app in the setting interface through accessibility service
Redis common interview questions
Use Chenxi bookkeeping book to analyze the balance of revenue and expenditure of each account in a certain period of time
Tencent map and high logo removal method
22年字节跳动飞书人力套件三面面经
Usage of functions decode() and replace() in SQL
QT error: no matching member function for call to ‘connect‘