Algorithms—123.Best Time to Buy and Sell Stock III
来源:互联网 发布:创维网络电视50价格 编辑:程序博客网 时间:2024/06/05 11:19
思路:限制交易两次。首先,求出单次交易最大利润,然后,只有2种可能,与此次交易无关,那么不在左侧就在右侧,再求一次,或者是与此次交易有关,那么在此次交易的日期限制内找出一段利润最低(负值)。比较左侧,右侧,中间的负值的绝对值的大小。
这段代码写的比较丑,凑合的看吧。sum3是中间的负值。
public class Solution { public int maxProfit(int[] prices) {if (prices.length <= 1) {return 0;}int[] change = new int[prices.length - 1];for (int i = 0; i < change.length; i++) {change[i] = prices[i + 1] - prices[i];}int sum0 = 0;int s0 = 0;int b=0;int e=0;int begin0 = 0;int end0 = 0;for (int i = 0; i < change.length; i++) {s0 += change[i];if (s0 < 0) {s0 = 0;b=i+1;e=i+1;}if (change[i] > 0) {e=i;}if (s0 > sum0) {sum0 = s0;begin0=b;end0=e;}}int sum1 = 0;int s1 = 0;for (int i = 0; i <begin0; i++) {s1 += change[i];if (s1 < 0) {s1 = 0;}if (s1 > sum1) {sum1 = s1;}}int sum2 = 0;int s2 = 0;for (int i = end0+1; i <change.length; i++) {s2 += change[i];if (s2 < 0) {s2 = 0;}if (s2 > sum2) {sum2 = s2;}}int sum3 = 0;int s3 = 0;for (int i = begin0+1; i <end0; i++) {s3 += change[i];if (s3 > 0) {s3 = 0;}if (s3 < sum3) {sum3 = s3;}}return sum0+Math.max(0-sum3, Math.max(sum1, sum2));}}
0 0
- Algorithms—123.Best Time to Buy and Sell Stock III
- Algorithms—121.Best Time to Buy and Sell Stock
- LeetCode 123. Best Time to Buy and Sell Stock III
- 123.Best Time to Buy and Sell Stock III
- [Leetcode]123.Best Time to Buy and Sell Stock III
- [Leetcode] 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- [leetcode] 123.Best Time to Buy and Sell Stock III
- 【leetcode】123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- [leetcode] 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- leetcode 123. Best Time to Buy and Sell Stock III
- leetcode 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- [LeetCode] 123. Best Time to Buy and Sell Stock III
- C语言程序设计笔记(四)
- IO-字节流与字符流
- maven 之中央仓库和私有仓库实战
- LeetCode 题解(111): Longest Valid Parentheses
- 零基础项目制学习python(二)
- Algorithms—123.Best Time to Buy and Sell Stock III
- BestCoder #45 1003 Dylans loves tree
- 查看android程序的CPU和内存消耗情况
- 黑马程序员---多线程
- LeetCode——Plus One
- 黑马程序员-线程
- Docker ubuntu 安装
- 用latex排版中的对象旋转问题
- 进程间通信(10) - 网络套接字(socket)[1]