121. 122.123 Best Time to Buy and Sell Stock

来源:互联网 发布:微信点菜系统源码 编辑:程序博客网 时间:2024/06/06 09:29

Best Time to Buy and Sell Stock

Example 1:

Input: [7, 1, 5, 3, 6, 4]Output: 5max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1]Output: 0In this case, no transaction is done, i.e. max profit = 0.

   1. 找出最大和最小

2. 如果prices[I] < min 对调

if(prices.length == 0) return 0;int min = prices[0];int max = 0;for (int i = 1; i < prices.length; i++) {if(prices[i] < min) min = prices[i];else if(prices[i] - min > max) {max = prices[i] - min;}}return max;

121. Best Time to Buy and Sell StockII
1. 不限交易次数,只要可以赚就交易
if(prices.length == 0) return 0;        int max = 0;        for(int i = 1; i < prices.length; i++) {            if(prices[i] > prices[i - 1]) {                max += prices[i] - prices[i - 1];            }        }        return max;

123. Best Time to Buy and Sell Stock III
限制在两次交易内
1.  先计算出子序列[0,...,i]中的最大利润,用一个数组保存下来,那么时间是O(n)。
2.  逆向扫描,计算子序列[i,...,n-1]上的最大利润,这一步同时就能结合上一步的结果计算最终的最大利润了,这一步也是O(n)。
public int maxProfit(int[] prices) {        if(prices.length == 0) return 0;        int max = 0;                //前0 - i个        int[] one = new int[prices.length];        one[0] = 0;        int min = prices[0];        for(int i = 1; i < prices.length; i++) {            if(prices[i] < min) min = prices[i];            else if(prices[i] - min > max) max = prices[i] - min;            one[i] = max;        }                //后 i - n-1 逆向遍历        int[] two = new int[prices.length];        two[prices.length - 1] = 0;        max = 0;        int high = prices[prices.length - 1];        for(int i = prices.length - 2; i >= 0; i--) {            if(prices[i] > high) high = prices[i];            else if(high - prices[i] > max) max = high - prices[i];            two[i] = max;        }                //再进行划分,分别计算两个部分        for(int i =0; i < prices.length; i++) {            int ret = one[i] + two[i];            if(max < ret) max = ret;        }                return max;    }






0 0