Best Time to Buy and Sell Stock III
来源:互联网 发布:淘宝网安卓版 编辑:程序博客网 时间:2024/06/18 10:29
Q:
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.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Solution:
The first for loop calculates the maximum profit from day 0 to i, and the second for loop calculates the maximum profit from i to n-1. Return the maximum sum of two values.
public class Solution { public int maxProfit(int[] prices) { if (prices.length == 0 || prices.length == 1) return 0; int[] forward = new int[prices.length]; forward[0] = 0; int min = Integer.MAX_VALUE; for (int i = 0; i < prices.length-1; i++) { if (prices[i+1] >= prices[i]) { min = Math.min(min, prices[i]); forward[i+1] = prices[i+1] - min; } } int max = 0; // the max price in the reverse order int reverseMax = prices[prices.length-1]; int ret = 0; for (int i = prices.length-2; i >= 0; i--) { max = Math.max(max, reverseMax - prices[i]); ret = Math.max(ret, forward[i] + max); reverseMax = Math.max(reverseMax, prices[i]); } return ret; }}
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
- Best Time to Buy and Sell Stock III
- 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
- Best Time to Buy and Sell Stock III
- 【leetcode】Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- LeetCode - Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- 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
- 类 Mac
- 获得文件夹的路径
- WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED解决方法
- 做产品经理如何起步
- HBase总结(十二)Java API 与HBase交互实例
- Best Time to Buy and Sell Stock III
- Ajax级联实例
- 解决高并发中出现Too many open files问题
- Valid signing identity not found解决办法(原有IDP私钥丢失)及Certificate、App ID、Devices、Provisioning Profiles之间区别
- 交叉编译sqlite3
- 从 windows 到 linux(1):g++不能用函数内定义的类型做模板参数
- 第7周项目1电阻串联
- QtQuick桌面应用开发指导 4)动态管理Note对象_B 5)外观加强 6)更多改进
- linux对源文件的编译过程