当前位置:网站首页>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
边栏推荐
- Machine learning theory (7): kernel function kernels -- a way to help SVM realize nonlinear decision boundary
- [popular science] CRC verification (I) what is CRC verification?
- Yyds dry goods inventory stringprep --- Internet string preparation
- Loop path
- Machine learning theory (8): model integration ensemble learning
- mysql_ Download and installation of Linux version
- Esp32 drive encoder -- siq-02fvs3 (vscade + IDF)
- Esp32 (UART ecoh) - serial port echo worm learning (2)
- The corresponding permissions required to automatically open the app in the setting interface through accessibility service
- One of the reasons why the WebView web page cannot be opened (and some WebView problem records encountered by myself)
猜你喜欢

ctfshow-web361(SSTI)

ESP32 LVGL8. 1 - textarea text area (textarea 26)

Use Chenxi bookkeeping book to analyze the balance of revenue and expenditure of each account in a certain period of time

STM32: LCD显示

Iptables - L executes slowly

Setting up keil environment of GD single chip microcomputer

ESP32 LVGL8. 1 - img picture (IMG 20)

mysql_linux版本的下载及安装详解

Use bitnami / PostgreSQL repmgr image to quickly set up PostgreSQL ha

机器学习实战 -朴素贝叶斯
随机推荐
程序员如何快速开发高质量的代码?
Screenshot using projectmediamanager
纠结
ESP32 LVGL8. 1 - label (style 14)
Introduction to ROS learning notes (I)
12个例子夯实promise基础
iptables初探
ESP32 LVGL8. 1 - checkbox (checkbox 23)
玻璃体中的硫酸软骨素
Esp32 (UART 485 communication) - 485 communication of serial port (3)
机器学习理论基础篇--关于机器学习的一些术语
Implementation of TCP UDP communication with golang language
Use of kotlin collaboration in the project
Go 语言 GUI 框架 fyne 中文乱码或者不显示的问题
Chondroitin sulfate in vitreous
How can programmers quickly develop high-quality code?
ctfshow-web361(SSTI)
解决:cnpm : 无法加载文件 ...\cnpm.ps1,因为在此系统上禁止运行脚本
Treatment of incomplete display of listview height
关于unity文件读取的操作(一)