leetcode Best Time to Buy and Sell Stock III
来源:互联网 发布:ubuntu怎么配置ip 编辑:程序博客网 时间:2024/05/16 18:05
题目要求之多两次事务得到的最大收益。
较为自然的联想到以时间 i 为分界点,求出 0- - -i 与 i+1- - -end之间的最大效益,分别比较大小以及两者之和的大小即可获得最大利润。
代码(超时)
class Solution {public: int maxProfit(vector<int> &prices) { maxNum = 0; if(prices.size()==0||prices.size()==1) return 0; for(int i = prices.size()-1; i >= 0; --i) { int sum1 = getMax(0, i-1, prices); int sum2 = getMax(i, prices.size()-1, prices); int sum3 = sum1+sum2; maxNum = max(sum3, max(sum1, sum2)); } return maxNum; } int getMax(int start, int end, vector<int> &prices) { if(start==end||start>end||start<0||end<0) return 0; int maxSold = prices[end]; int maxNum = 0; for(int i = end; i >= 0; --i) { maxSold = max(prices[i], maxSold); maxNum = max(maxNum, maxSold - prices[i]); } return maxNum; } private: int maxNum;};
上述算法时间复杂度为O(n^2)
参考网上资料可以优化代码(Accepted)
class Solution {public: int maxProfit(vector<int> &prices) { maxNum = 0; int len = prices.size(); if(len<=1) return 0; int maxFromHead[len]; int minBought = prices[0]; int maxPrice = 0; for(int i = 0; i < prices.size(); ++i) { minBought = min(minBought, prices[i]); maxPrice = max(maxPrice, prices[i]-minBought); maxFromHead[i] = maxPrice; } int maxSold = prices[len-1]; maxPrice = 0; maxNum = maxFromHead[len-1]; for(int i = len-1; i >= 0; --i) { maxSold = max(maxSold, prices[i]); maxPrice = max(maxPrice, maxSold - prices[i]); maxNum = max(maxNum, maxPrice+maxFromHead[i-1]); } return maxNum; } private: int maxNum;};
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
- ARM平台Linux内核空指针异常处理流程
- 项目分配问题
- java 获取文件名(不包括文件的后缀)和文件重命名
- UVA - 10534Wavio Sequence(LIS)
- usb serial驱动流程分析
- leetcode Best Time to Buy and Sell Stock III
- 在ROS的PPPOE IP变的时候自动修改DNS记录,实现DDNS
- codechef August Challenge 2014 第五个题目
- hdu2417并查集
- 一个带动画的页面底部的TabBar的实现
- 异常处理表
- 桥接模式处理下机计算金额问题
- WDF驱动模型
- Android事件处理