和最大连续子串续——和最大连续子矩阵

继上一节学习了和最大连续子串,推广到和最大连续子矩阵,以二维为例,子矩阵是矩阵行和列的组合,参考:http://blog.sina.com.cn/s/blog_a782701501016636.html

代码如下:

package programming;

/**最大和的连续子矩阵
 * 将连续子矩阵看做是一维连续子串,然后利用和最大连续子串方法,求出连续子串,进而求出子矩阵
 * @author ywf
 *
 */
public class MaxSumSubMatrix {

    /**
     * @param args
     */
    public static void main(String[] args) {
        int[][] A =  {{0, -2,  -7,  0},
                  {9 , 2 , -6,  2},
                  {-4 , 1 ,-4 , 1},
                  {-1 , 8 ,  0 ,-2}};
        int[] temp = new int[A[0].length];
        int subMaxSum = Integer.MIN_VALUE;
        int colStart = -1;
        int colEnd = -1;
        int rowStart = -1;
        int rowEnd = -1;
        //矩阵压缩
        for(int i = 0 ;i<A.length;i++){            
            for(int j = i;j<A[i].length;j++){
                for(int h = i;h<=j;h++){
                    for(int k = 0;k<temp.length;k++){                        
                            temp[k] += A[h][k];                                        
                    }
                }
                int[] tempMax = getResult4(temp);
                if(tempMax[2]>subMaxSum){
                    subMaxSum = tempMax[2];
                    colStart = tempMax[0];
                    colEnd = tempMax[1];
                    rowStart = i;
                    rowEnd = j;
                }
                temp = new int[A[0].length];
            }            
        }
        //输出和最大子矩阵
        for(int i = rowStart;i<=rowEnd;i++){
            for(int j = colStart;j<=colEnd;j++){
                System.out.print(A[i][j]+" ");
            }
            System.out.println();
        }
        System.out.println("sum:"+subMaxSum);

    }
    public static int[] getResult4(int[] array) {
        int[] result = new int[3];
        int rmax = Integer.MIN_VALUE;//当前最大的和
        int sum = Integer.MIN_VALUE;//当前的和
        int start = -1;//最大子串的起始下标
        int end = -1;//最大子串的结束下标
        for (int i = 0; i < array.length; i++) {
            if (sum > 0) {
                sum += array[i];
            } else {
                sum = array[i];
                if(sum>rmax){
                    start = i;
                }                
            }
            if (sum > rmax) {
                rmax = sum;
                end = i;
            }

        }
        result[0] = start;
        result[1] =end ;
        result[2] = rmax;
        return result;
    }
}

 http://yunpan.cn/cyRA3J9ztrG5N  提取码 d68b

转载于:https://www.cnblogs.com/yuwenfeng/p/4121671.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值