Leetcode Best Time to Buy and Sell Stock III
来源:互联网 发布:知乎关注最多的问题 编辑:程序博客网 时间:2024/06/06 12:50
Leetcode Best Time to Buy and Sell Stock III,本算法的关键为找出其动态子结构。可以发现,序列中的最小值可以做为其的一个分割,令左边序列为left,右边的序列为right,整个串为whole,可以推出当前串的最大值一定是在:a.左序列一次transaction最大值(left_max)与右序列一次transaction最大值(right_max)之和,b.整个序列一次交易最大值;两者之间产生。有一种情况.
class Solution {public: int maxProfit(vector<int>& prices) { int max = 0; findMax(prices, max, 0, prices.size() - 1); return max; } int findMax(vector<int>& prices, int& max, int start, int end) { if (start >= end) { return 0; } int begin = start; int cur_max = 0; int left_max = 0; int right_max = 0; int min_pos = -1; int pre = start; int descent_count = 0; int backward = 0; for (int i = start + 1; i <= end; i ++) { // get the consective descent element num if (prices[i] <= prices[pre]) { descent_count ++; } else { descent_count = 0; } // get the minest element if ((prices[i] <= prices[min_pos] || min_pos == -1) && prices[i] < prices[pre]) { min_pos = i; backward = descent_count; } // calculate the max profite by one transaction if (prices[i] < prices[begin]) { begin = i; } else { int tmp = prices[i] - prices[begin]; cur_max = tmp > cur_max? tmp : cur_max; } pre = i; } // calculate the left and the right if (min_pos != -1) { left_max = findMax(prices, max, start, min_pos - backward); right_max = findMax(prices, max, min_pos, end); } // get the current max if (cur_max > max) { max = cur_max; } if (left_max + right_max > max) { max = left_max + right_max; } return cur_max; }};
test: ./a.out 3 2 4 2 5 7 2 4 9 0re: 12
0 0
- LeetCode Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock III
- leetcode 16: Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- leetcode 62: Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- 【leetcode】Best Time to Buy and Sell Stock III
- LeetCode - Best Time to Buy and Sell Stock III
- LeetCode之Best Time to Buy and Sell Stock III
- [LeetCode]Best Time to Buy and Sell Stock III
- LeetCode: Best Time to Buy and Sell Stock III
- [Leetcode]Best Time to Buy and Sell Stock III
- [leetcode]Best Time to Buy and Sell Stock III
- leetcode题目:Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- LeetCode-Best Time to Buy and Sell Stock III
- android weight(权重)的具体分析
- LightOJ 1138 - Trailing Zeroes (III)(二分&阶乘末尾0的个数)
- 凭啥Java的运行环境称虚拟机,Python的只能称解释器
- 今年第一次面试
- Linux 设备驱动中的 I/O模型(二)—— 异步通知和异步I/O
- Leetcode Best Time to Buy and Sell Stock III
- grep排除搜索的目录
- 视频编解码学习之二:数字视频
- Interop with PROPVARIANTs in .NET -- C# 调用C++ COM 系列笔记
- ubuntu14.04安装telnet
- Java实现抽象工厂模式+java的反射的机制
- Android中的门面模式
- 性能调优攻略
- rfc5245--概要翻译