股票买卖

来源:互联网 发布:熹妃传刷元宝软件 编辑:程序博客网 时间:2024/04/24 20:32
1. 只允许买卖一次股票,求最大利润
2. 允许买卖多次
3. 只允许买卖最多两次股票

3. 只许买卖最多两次股票,求最大利润
中心思想:对每一个element i,计算0 -> i 和i->n-1 两个段的最大利润。
    public int maxProfit(int[] prices) {        int n = prices.length;        if (n <= 1) {            return 0;        }        int[] leftProfit = new int[n];        int[] rightProfit = new int[n];        leftProfit[0] = 0;        rightProfit[n-1] = 0;        int low = Integer.MAX_VALUE;        int high = Integer.MIN_VALUE;        int max = 0;            for (int i = 1; i < n; i++) {            low = Math.min(low, prices[i-1]);            leftProfit[i] = Math.max(prices[i] - low, leftProfit[i-1]);        }                for (int i = n-2; i >= 0; i--) {            high = Math.max(high, prices[i+1]);            rightProfit[i] = Math.max(high - prices[i], rightProfit[i+1]);            max = Math.max(max, leftProfit[i] + rightProfit[i]);        }        return max;    }


1. 买卖一次
    public intmaxProfit(int[] prices) {       int profit = 0;       int min = Integer.MAX_VALUE;       if (prices.length <= 1) {           returnprofit;       }       for (int i = 0; i <prices.length; i++) {           intcurProfit = prices[i] - min;           if(curProfit > profit) {              profit = curProfit;           }           if(prices[i] < min) {              min = prices[i];           }       }       return profit;    }


2. 允许多次买卖股票,求最大利润
    public intmaxProfit(int[] prices) {       int profit = 0;       int min = Integer.MAX_VALUE;       if (prices.length <=1) {           return0;       }       int i = 0;       while (i < prices.length) {           while (i< prices.length-1 &&prices[i] > prices[i+1]) {              i++;           }           int j =i;           while (j< prices.length-1 &&prices[j] < prices[j+1]) {              j++;           }           profit +=prices[j] - prices[i];           i =j+1;       }       return profit;    }


3. 只许买卖最多两次股票,求最大利润
中心思想:对每一个element i,计算0 -> i 和i->n-1 两个段的最大利润。
    public int maxProfit(int[] prices) {        int n = prices.length;        if (n <= 1) {            return 0;        }        int[] leftProfit = new int[n];        int[] rightProfit = new int[n];        leftProfit[0] = 0;        rightProfit[n-1] = 0;        int low = Integer.MAX_VALUE;        int high = Integer.MIN_VALUE;        int max = 0;            for (int i = 1; i < n; i++) {            low = Math.min(low, prices[i-1]);            leftProfit[i] = Math.max(prices[i] - low, leftProfit[i-1]);        }                for (int i = n-2; i >= 0; i--) {            high = Math.max(high, prices[i+1]);            rightProfit[i] = Math.max(high - prices[i], rightProfit[i+1]);            max = Math.max(max, leftProfit[i] + rightProfit[i]);        }        return max;    }

0 0