leetcode做题总结,题目Best Time to Buy and Sell Stock 2012/10/30

来源:互联网 发布:知识产权 淘宝 编辑:程序博客网 时间:2024/03/28 21:40

之前没想出来,今天忘了是看算法导论还是另一本算法书讲到了最大子序列,正好就拿这道题做例子,一种方法是二分递归两边的最大子序列,然后再合并,计算穿过中界线的最大序列进行递归求最大值。还有一种更好的方法是类似于GAS 那道题,求出变化量数组,然后相加,如果总和为负,则序列从新开始。这样只需O(n)的时间复杂度。


public int maxProfit(int[] prices) {        int num = prices.length;        if(num==0||num==1)return 0;        int[] pr = new int[num-1];        for(int i=0;i<num-1;i++){            pr[i]=prices[i+1]-prices[i];        }        int max=0;        int thi=0;        for(int i=0;i<num-1;i++){            thi=thi+pr[i];            if(thi>max) max=thi;            if(thi<0) thi=0;        }        return max;    }

Update 2015/08/21: 思路同上,只是优化了一下


public class Solution {    /**     * @param prices: Given an integer array     * @return: Maximum profit     */    public int maxProfit(int[] prices) {        // write your code here        int len = prices.length - 1;        for (int i = 0; i< len; i++){            prices[i] = prices[i + 1] - prices[i];        }        int global = 0;        int local = 0;        for (int i = 0; i< len; i++){            local = local + prices[i];            if (local < 0){                local = 0;            }            global = Math.max(global, local);        }        global = Math.max(global, local);        return global;    }}


0 0