leetcode_Best Time to Buy and Sell Stock III
来源:互联网 发布:macbook air卸载软件 编辑:程序博客网 时间:2024/06/03 17:42
描述:
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
思路:
给两次交易机会,让求最大的利润,先从左向右求到当前节点的最大利润并将其存储到一个数组profit1[ ]中,然后从右向左求到当前节点的最大利润并将其存储到一个数组profit2[ ]中,然后从前向后遍历求到某个节点时其左右部分的利润相加,然后和当前最大利润相比从而得出最大利润。
代码:
public int maxProfit(int[] prices) { if(prices==null) return 0; int len=prices.length; if(len==0) return 0; int maxProfit=0; int tempPre=prices[0]; int tempCur=0; prices[0]=0; for(int i=1;i<len;i++) { tempCur=prices[i]; prices[i]=prices[i]-tempPre; tempPre=tempCur; }maxProfit=getMaxProfit(prices); return maxProfit; } public int getMaxProfit(int profit[]) { int len=profit.length; int profitFromEnd[]=new int[len]; for(int i=0;i<len;i++) profitFromEnd[i]=profit[i]; for(int i=1;i<len;i++) { if(profit[i-1]>0) profit[i]=profit[i-1]+profit[i]; } for(int i=len-2;i>=0;i--) { if(profitFromEnd[i+1]>0) profitFromEnd[i]=profitFromEnd[i]+profitFromEnd[i+1]; } int max=profit[0]; for(int i=1;i<len;i++) { if(max<profit[i]) max=profit[i]; profit[i]=max; } max=profitFromEnd[len-1]; for(int i=len-2;i>=0;i--) { if(max<profitFromEnd[i]) max=profitFromEnd[i]; profitFromEnd[i]=max; } int maxProfit=0; int tempMaxProfit=0; int count=len-1; for(int i=0;i<count;i++) { tempMaxProfit=profit[i]+profitFromEnd[i+1]; if(maxProfit<tempMaxProfit) maxProfit=tempMaxProfit; } return maxProfit; }
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_Best Time to Buy and Sell Stock
- LeetCode_best-time-to-buy-and-sell-stock
- LeetCode_Best Time to Buy and Sell Stock
- Leetcode_Best Time to Buy and Sell Stock
- leetcode_Best Time to Buy and Sell Stock II
- LeetCode_best-time-to-buy-and-sell-stock-ii
- LeetCode_Best Time to Buy and Sell Stock II
- Leetcode_Best Time to Buy and Sell Stock II
- Leetcode_best-time-to-buy-and-sell-stock(c++ and python version)
- Leetcode_best-time-to-buy-and-sell-stock-ii(c++ and python version)
- 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
- Android aapt介绍
- 我对JavaScript原型的理解
- MFC之MessageBox用法
- ios学习(四) GCDiscreetNotificationView提示视图
- iOS开发经验技巧之UITableViewCell的重用
- leetcode_Best Time to Buy and Sell Stock III
- 2015年大一下第8周项目4-点类派生直线类
- result
- ubuntu创建wifi热点(手机可识别)
- .HTM与.HTML的区别
- cookie和session杂记
- Harry Potter and the Chamber of Secrets
- winform配置文件的简单使用
- 基于Matlab的数字水印技术研究