Java--最大子序列和實現

來源:互聯網
上載者:User

標籤:--   color   最大值   java   ...   最佳化   最大   log   lis   

 

package com.dongbin.test;/** * 最大子序列和 --分治法 *  * @author dongbin * */public class MaxSubListSum {    /**     * 最大子序列的實現方法     *      * @param arr     *            --數組     * @param left     * @param right     * @return     */    public static int maxsubListSum(int arr[], int left, int right) {        if (left == right) {// arr.length==1            if (arr[left] > 0) {                return arr[left];            } else {                return 0;            }        }        // 劃分數組        int center = (left + right) / 2;        int maxLeftSum = maxsubListSum(arr, left, center);// 左邊最大值        int maxRightSum = maxsubListSum(arr, center + 1, right);// 右邊最大值        // 左邊求和        int maxLeftBorderSum = 0, leftBorderSum = 0;        for (int i = center; i >= left; i--) {            leftBorderSum += arr[i];            if (leftBorderSum > maxLeftBorderSum) {                maxLeftBorderSum = leftBorderSum;            }        }        // 右邊求和        int maxRightBorderSum = 0, rightBorderSum = 0;        for(int i = center+1;i<=right;i++){            rightBorderSum += arr[i];            if(rightBorderSum>maxRightBorderSum){                maxRightBorderSum = rightBorderSum;            }                    }                return maxList(maxLeftSum,maxRightSum,maxLeftBorderSum+maxRightBorderSum);            }        /**     * 擷取 多個Id 的最大值     * @param elements     * @return     */    private static  int maxList(int... elements){        int max = 0;        for(int i = 0;i<elements.length;i++){            if(elements[i]>max){                max = elements[i];            }        }        return max;    }        public static void main(String[] args) {        int[] a = {4,-3,5,-2,-1,2,6,-2};        System.out.println(maxsubListSum(a, 0, a.length-1));    }}

 

/**     * 最佳化最大子序列     * @param arr     * @return     */    public static int optMaxSubListSum(int [] arr){        int maxSum = 0,temp = 0;        for(int i=0;i<arr.length;i++){            temp += arr[i];            if(temp>maxSum){                maxSum = temp;            }                        if(temp<0){                temp = 0;            }        }                return maxSum;    }

 

Java--最大子序列和實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.