Leetcode123 hard

来源:互联网 发布:我要复仇知乎 编辑:程序博客网 时间:2024/06/09 23:29

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.

解析:很容易想出将原有数组分为两个部分,分别找出左半部分和右半部分最大的利润值。从第二个位置开始分,然后将两边利润值相加找到两次买入和卖出的最大利润,这里的技巧就是使用两个数组分别记录以某个位置分隔,左半部分和右半部分的最大利润值。求解利润值关键在于如何求得某一段数组的最大利润,并是在O(n)复杂度内完成。在扫描时,我们希望买入值尽量的小,卖出值尽量的大,所以当某个位置的加个小于买入价格时,需要更新买入价格。同时利润值为当前的价格减掉最小的买入价格,最后找出最大利润即可。由于是顺序扫描,不会出现卖出是在买入之前。同理我们可以逆着数组扫描,但是注意逆着扫描就一定要记录最大卖出值。然后同理找出最大利润。


以下附已AC的JAVA源代码:

// 123hpublic int maxProfit123(int[] prices) {if (prices == null || prices.length < 2) {return 0;}if (prices.length == 2) {if (prices[1] > prices[0]) {return prices[1] - prices[0];}return 0;}int prL[] = new int[prices.length];int prR[] = new int[prices.length];int bugMin = prices[0];int proMax = 0;for (int i = 0; i < prices.length; i++) {int pro = prices[i] - bugMin;proMax = pro > proMax ? pro : proMax;if (prices[i] < bugMin) {bugMin = prices[i];}prL[i] = proMax;}int sellMax = prices[prices.length - 1];proMax = 0;for (int i = prices.length - 1; i >= 0; i--) {int pro = sellMax - prices[i];proMax = pro > proMax ? pro : proMax;if (prices[i] > sellMax) {sellMax = prices[i];}prR[i] = proMax;}proMax = 0;for (int mid = 1; mid < prices.length - 1; mid++) {int pro = prL[mid] + prR[mid];proMax = pro > proMax ? pro : proMax;}return proMax;}



0 0
原创粉丝点击