Best Time to Buy and Sell Stock with Transaction Fee问题及解法
来源:互联网 发布:js中的settimeout 编辑:程序博客网 时间:2024/05/23 21:23
问题描述:
Your are given an array of integers prices
, for which the i
-th element is the price of a given stock on day i
; and a non-negative integer fee
representing a transaction fee.
You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)
Return the maximum profit you can make.
示例:
Input: prices = [1, 3, 2, 8, 4, 9], fee = 2Output: 8Explanation: The maximum profit can be achieved by:
问题分析:
有题可知,每一天都会存在股票交易的两种状态-----buy or sell,我们定义如下的状态转换:
buy[i] --- 第i天之前已buy为结束状态的序列所获得的最大利益
sell[i] --- 第i天之前以sell为结束状态的序列所获得的最大利益
那么
buy[i] = max(buy[i - 1],sell[i] - prices[i])
sell[i] = max(sell[i - 1],buy[i - 1] + prices[i] - fee)
过程详见代码:
class Solution {public: int maxProfit(vector<int>& prices, int fee) { int buy(-prices[0]), sell(0), prev_buy; for (int i = 1; i < prices.size(); i++){prev_buy = buy;buy = max(sell - prices[i], buy);sell = max(prev_buy + prices[i] - fee, sell) ;}return sell; }};
阅读全文
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
- 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
- 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
- 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]
- [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
- 计算机网络面试题
- UIView动画简介
- TCP/IP学习--------------- MSS
- 原始Jdbc开发
- Hadoop Yarn
- Best Time to Buy and Sell Stock with Transaction Fee问题及解法
- window命令窗口的跳转命令——cd
- setsockopt中参数之SO_REUSEADDR的意义(转)
- boost
- javascript模块化编程
- 小程序打开网页,微信小程序web-view打开html网页
- spring boot--整合spring session实现session共享以及cookie丢失问题解决
- centos 7 U盘安装教程
- Azure 中部署Gitlab的方法