当前位置:网站首页>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
边栏推荐
- Excel intercept text
- Machine learning theory (8): model integration ensemble learning
- C language simulates entering and leaving the stack, first in first out, first in first out, shared memory
- The first leg of the national tour of shengteng AI developer creation and enjoyment day was successfully held in Xi'an
- Click the input box to pop up the keyboard layout and move up
- From technical system to business insight, the closing chapter of the practice of small and medium-sized R & D team structure
- Nacos cluster construction and MySQL persistence configuration
- Database computer experiment 4 (data integrity and stored procedure)
- WebView saves the last browsing location
- Kettle paoding jieniu Chapter 17 text file output
猜你喜欢
随机推荐
K210串口通信
Introduction to ROS learning notes (II)
QT curve / oscilloscope customplot control
Setting up keil environment of GD single chip microcomputer
机器学习理论之(8):模型集成 Ensemble Learning
Practice of Druid SQL and security in meituan review
Esp32 (UART 485 communication) - 485 communication of serial port (3)
mysql_linux版本的下載及安裝詳解
Treatment of incomplete display of listview height
ESP32 LVGL8. 1 - input devices (input devices 18)
#yyds干货盘点#stringprep --- 因特网字符串预备
机器学习理论之(7):核函数 Kernels —— 一种帮助 SVM 实现非线性化决策边界的方式
Daily CISSP certification common mistakes (April 19, 2022)
Download xshell 6 and xftp6 official websites
Domestic GD chip can filter
Redis common interview questions
Daily CISSP certification common mistakes (April 18, 2022)
ctfshow-web362(SSTI)
简化路径(力扣71)
MVVM model