[Leetcode 123, Hard] Best Time to Buy and Sell Stock III
2015-07-24 08:40
633 查看
Problem:
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Analysis:
Solutions:
C++:
Python:
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Analysis:
Solutions:
C++:
int maxProfit(vector<int> &prices) { if(prices.size() <= 1) return 0; int max_left = 0; vector<int> maxs_from_left; maxs_from_left.push_back(0); int min_price = prices[0]; for(int i = 1; i < prices.size(); ++i) { if(min_price > min(prices[i - 1], min_price)) min_price = prices[i - 1]; if(max_left < prices[i] - min_price) max_left = prices[i] - min_price; maxs_from_left.push_back(max_left); } int max_two_trans = maxs_from_left[maxs_from_left.size() - 1]; int max_price = prices[prices.size() - 1]; for(int i = prices.size() - 2; i >= 1; --i) { if(max_price < max(max_price, prices[i])) max_price = prices[i]; if(max_two_trans < maxs_from_left[i - 1] + max_price - prices[i]) max_two_trans = maxs_from_left[i - 1] + max_price - prices[i]; } return max_two_trans; }Java:
Python:
相关文章推荐
- No parameter name specified for argument of type
- 浅谈javascript获取元素transform参数
- LeetCode #20 Valid Parentheses
- 如何修改mysql配置中的字符集
- 用new和delete运算符进行动态分配和撤销存储空间
- Android虚拟机上安装和卸载APK程序
- Best time to buy and sell stocks IV
- [Leetcode 122, Medium] Best Time to Buy and Sell Stock II
- Cordys HLJ项目前端常用语法
- android答题系统(三):答题部分的实现
- UVA-10339 Watching Watches
- ARC机制之__weak,__autorelease详解
- 简析Swift和C的交互
- 简单、优美的Dialog
- 面试题 收集请求k千里马
- Windows 10 手机版性功能 统一管理应用获取地理位置的权限
- Swift开发必备技巧:static和class的使用
- 解读c的申明上
- android答题系统(二):实现主界面入口和查询数据
- Remove Element