• 最大子数组



    /**
    * 最大子数组问题 采用分治策略
    * @author wu
    *
    */
    public class FindMaxMumSubarray {

    returnParameter rtP=new returnParameter();
    returnParameter rtPleft=new returnParameter();
    returnParameter rtPRight=new returnParameter();
    returnParameter rtPCorss=new returnParameter();

    public returnParameter FindMaxMumSubbarray1(int a[],int low,int high){
    int mid;
    if(low==high){//there is only one element in array a[]
    rtP.sum=a[low];
    rtP.low=low;
    rtP.high=high;
    rtP.print();
    return rtP;

    }
    else{

    mid=(low+high)/2;
    System.out.println("(1)");
    rtPleft= FindMaxMumSubbarray1(a, low, mid);
    System.out.println("(2)");
    rtPRight=FindMaxMumSubbarray1(a, mid+1, high);
    System.out.println("(3)");
    rtPCorss=FindMaxCorssingSubarray(a,low,mid,high);

    if(rtPleft.sum>=rtPCorss.sum && rtPleft.sum>=rtPRight.sum){
    rtPleft.print();
    return rtPleft;
    }

    else if(rtPRight.sum>=rtPleft.sum && rtPRight.sum>=rtPCorss.sum){
    rtPRight.print();
    return rtPRight;
    }

    else{
    rtPCorss.print();
    return rtPCorss;
    }
    }


    }


    private returnParameter FindMaxCorssingSubarray(int[] a, int low, int mid, int high) {
    returnParameter rtp=new returnParameter();
    int max_left = 0,max_right = 0;
    int left_sum=(int) -9.99e20;
    int sum=0;
    for(int i=mid;i>=low;i--){
    sum+=a[i];
    if(sum>left_sum){
    left_sum=sum;
    max_left=i;
    }
    }
    int right_sum=(int) -9.99e20;
    int sum1=0;
    for(int j=mid+1;j<=high;j++){
    sum1+=a[j];
    if(sum1>right_sum){
    right_sum=sum1;
    max_right=j;
    }
    }
    rtp.low=max_left;
    rtp.high=max_right;
    rtp.sum=left_sum+right_sum;
    return rtp;

    }
    }

  • 相关阅读:
    WP8.1通过StreamSocket连接C++服务器
    WP10通过StreamSocket连接C++服务器
    二维背包(两个限制条件)
    dp(多重背包)
    dp(完全背包)
    dfs(迷宫)
    bfs迷宫
    蚁人cp数
    二分(老死不相往来)
    前缀和(狼和野牛)
  • 原文地址:https://www.cnblogs.com/java-wgm/p/3614468.html
Copyright © 2020-2023  润新知