连续子数组和极值问题

Programming pearls 8 chapter question .

 

 

/**
* User: yiminghe
 * Date: 2009-2-16
 * Time: 15:40:11
 */
public class LongestSubArray {


    /**
     * 一维数组最大的连续子数组和 [ -1 ,2,3,-5]      return 5 [2,3]    O(n)
     *
     * @param a 一维数组
     * @return 最大的连续子数组和
     */
    public static int getLongestOne(int[] a) {
        int max = 0;
        int current = 0;
        for (int o : a) {
            current = Math.max(current + o, 0);
            max = Math.max(current, max);
        }
        return max;
    }


    /**
     * 2维数组最大的连续子数组和     O(m^2n)
     * [ -1 ,2,3,-5
     * 0 , 3, 5 , 0]
     * return 13
     * [ 2,3
     *   3,5]
     *
     * @param a2 2维数组
     * @param m  行数
     * @param n  列数
     * @return 最大的连续子数组和
     */
    public static int getLongestTwo(int[][] a2, int m, int n) {
        int[][] cache = new int[m][n + 1];
        int max = 0;
        for (int i = 0; i < m; i++) {
            cache[i][0] = 0;
            for (int j = 1; j < n + 1; j++) {
                cache[i][j] = cache[i][j - 1] + a2[i][j - 1];
            }


        }


        for (int i = 0; i < n - 1; i++)
            for (int j = i + 1; j < n; j++) {
                int[] t = new int[m];
                for (int k = 0; k < m; k++) {
                    t[k] = cache[k][j + 1] - cache[k][i];
                }

                max = Math.max(max, getLongestOne(t));
            }
        return max;

    }


    public static void main(String[] args) {
        int[] a = {-1, 2, 3, -5};
        int[][] b = {{-1, 2, 3, -5}, {0, 3, 5, 0}};

        System.out.println(getLongestOne(a));
        System.out.println(getLongestTwo(b, 2, 4));
    }


}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值