Best Time to Buy and Sell Stock with Transaction Fee
来源:互联网 发布:php artisan数据库 编辑:程序博客网 时间:2024/05/21 14:50
题目描述
解题思路
整理要点如下:
1.因为每笔交易都会有交易花费,所以不能无限制的交易
2.在你买股票之前一定要先把手中的股票卖掉
也就是说第i天要么有股票准备卖出去或者留着不卖,而第i天的股票可能是第i-1天没有卖的,与有可能是第i-1天卖之后第i天买的,所以抽象出来为了得到在第i天得到最大利益,用两个一维数组考虑。sold[i]代表第i天卖掉股票此时的最大利润,hold[i]代表第i天不卖股票的最大利润。
思考其递推公式:在第i天,如果要卖掉股票,那么总利润应该是hold[i-1](即第i-1天保留股票的利润)加上此时卖出的price减去交易费用,跟sold[i-1]比,取较大值;如果第i天不卖,那么就是i-1天卖了的利润减去今天买股票的price,和第i-1天不卖时的利润比较取其较大值。即:
sold[i] = max(sold[i - 1], hold[i - 1] + prices[i] - fee);
hold[i] = max(hold[i - 1], sold[i - 1] - prices[i]);
C ++代码实现
class Solution {public: int maxProfit(vector<int>& prices, int fee) { vector<int> sold(prices.size(), 0); vector<int> hold = sold; hold[0] = -prices[0]; for (int i = 1; i < prices.size(); ++i) { sold[i] = max(sold[i - 1], hold[i - 1] + prices[i] - fee); hold[i] = max(hold[i - 1], sold[i - 1] - prices[i]); } return sold.back(); }};
运行截图
阅读全文
0 0
- Best Time to Buy and Sell Stock with Transaction Fee
- Best Time to Buy and Sell Stock with Transaction Fee
- Best Time to Buy and Sell Stock with Transaction Fee
- 714. Best Time to Buy and Sell Stock with Transaction Fee
- LWC 55:714. Best Time to Buy and Sell Stock with Transaction Fee
- weekly contest 55 Best Time to Buy and Sell Stock with Transaction Fee
- Leetcode算法学习日志-714 Best Time to Buy and Sell Stock with Transaction Fee
- LeetCode714. Best Time to Buy and Sell Stock with Transaction Fee
- leetcode 714 Best Time to Buy and Sell Stock with Transaction Fee
- LeetCode #714 Best Time to Buy and Sell Stock with Transaction Fee
- LeetCode算法问题10 —— Best Time to Buy and Sell Stock with Transaction Fee
- 714. Best Time to Buy and Sell Stock with Transaction Fee
- 714. Best Time to Buy and Sell Stock with Transaction Fee
- Best Time to Buy and Sell Stock with Transaction Fee[LeetCode 714]
- Best Time to Buy and Sell Stock with Transaction Fee问题及解法
- [LeetCode] Algorithms-714. Best Time to Buy and Sell Stock with Transaction Fee
- [LeetCode] DP之 Best time to buy and sell stock with transaction fee
- leetcode练习 714. Best Time to Buy and Sell Stock with Transaction Fee
- makefile
- Redis学习笔记——(二)Redis访问/关闭防火墙
- 设计模式、设计原则、反模式
- ElasticSearch的安装与使用必知问题
- springboot整合mybatis一个简单的demo
- Best Time to Buy and Sell Stock with Transaction Fee
- POJ2631
- 160个练手CrackMe-036
- 1002. 写出这个数 (20) c++
- 阿里Maven仓库 -- Settings.xml
- CVPR 2017 Enhancing Detection Model for Multiple Hypothesis Tracking 阅读笔记
- 第五章 LR分析法
- 第九节 java数组的介绍,数组定义,数组排序,Arrays类静态方法使用,以及源码解析
- Java 23种设计模式之工厂方法模式