赞
踩
我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/
题目描述:
知识点:动态规划
枚举第一笔交易卖出的时间firstDealSell,对[0, firstDealSell]范围内的价格求解LeetCode121——买卖股票的最佳时机中的问题,得到结果result1,再对[firstDealSell, n - 1]范围内的价格再一次求解LeetCode121——买卖股票的最佳时机中的问题,其中n为prices数组的大小,得到结果result2,求result1 + result2的最大值。
时间复杂度是O(n ^ 2)。空间复杂度是O(1)。
当然,在此基础之上,结合LeetCode122——买卖股票的最佳时机II,我们可以做一些小小的优化。
对于第一次和第二次卖出的时间点,firstDealSell和secondDealSell,其之前的价格一定是一个上坡,其之后的价格一定是一个下坡,我们在价格坡顶卖出。
JAVA代码:
- public class Solution {
- public int maxProfit(int[] prices) {
- int result = 0;
- if(prices.length == 0){
- return result;
- }
- int firstDealSell; //第一笔交易在firstDealSell卖出
- int secondDealSell; //第二笔交易在secondDealSell卖出
- for(secondDealSell = prices.length - 1; secondDealSell > 0; secondDealSell--){
- if(prices[secondDealSell - 1] < prices[secondDealSell]){
- break;
- }
- }
- for(firstDealSell = 1; firstDealSell < prices.length; firstDealSell++){
- while(firstDealSell + 1 < prices.length && prices[firstDealSell + 1] >= prices[firstDealSell]){
- firstDealSell++;
- }
- int result1 = maxProfit(prices, 0, firstDealSell);
- int result2 = maxProfit(prices, firstDealSell &

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。