礼物的最大价值(Java实现)


public class E47MaxValueOfGifts {
    //礼物的最大价值

    public static int getMaxValue_Solution1(int[] value, int rows, int cols){
        if (value == null || (rows <= 0 && cols <= 0))
            return -1;
        //用二维数组记录达到(i,j)点礼物的最大价值
        int[][] maxValue = new int[rows][cols];
        for (int i = 0; i < rows; i ++){
            for (int j = 0; j < cols; j ++){
                int up = 0;
                int left = 0;
                if (i > 0)
                    up = maxValue[i - 1][j];
                if (j > 0)
                    left = maxValue[i][j - 1];
                maxValue[i][j] = Math.max(up, left) + value[i * rows + j];
            }
        }
        return maxValue[rows - 1][cols - 1];
    }

    public static int getMaxValue_Solution2(int[] value, int rows, int cols){
        if (value == null || (rows <= 0 && cols <= 0))
            return -1;
        //用一维数组记录当前行列j对应的礼物最大价值
        //当前行还未到达的列记录的仍是上一行的信息
        int[] maxValue = new int[cols];
        for (int i = 0; i < rows; i ++){
            for (int j = 0; j < cols; j ++){
                int up = 0;
                int left = 0;
                if (i > 0)
                    up = maxValue[j];
                if (j > 0)
                    left = maxValue[j - 1];
                maxValue[j] = Math.max(up, left) + value[i * rows + j];
            }
        }
        return maxValue[cols - 1];
    }

    //测试用例
    public static void main(String[] args){
        int[] value = {1, 10, 3, 8, 12, 2, 9, 6, 5, 7, 4, 11, 3, 7, 16, 5};
        System.out.println(E47MaxValueOfGifts.getMaxValue_Solution1(value, 4, 4)); //53
        System.out.println(E47MaxValueOfGifts.getMaxValue_Solution2(value, 4, 4)); //53
    }
}

你可能感兴趣的:(剑指offer)