|
| 1 | +package javacode.solutions; |
| 2 | + |
| 3 | +// [Problem] https://leetcode.com/problems/maximum-number-of-points-with-cost |
| 4 | +class MaximumNumberOfPointsWithCost { |
| 5 | + // Dynamic programming |
| 6 | + // O(m * n) time, O(n) space |
| 7 | + // where m = row size, n = column size |
| 8 | + public long maxPoints(int[][] points) { |
| 9 | + int rowSize = points.length, colSize = points[0].length; |
| 10 | + long[] prevRow = new long[colSize]; |
| 11 | + for (int col = 0; col < colSize; col++) { |
| 12 | + prevRow[col] = points[0][col]; |
| 13 | + } |
| 14 | + for (int row = 1; row < rowSize; row++) { |
| 15 | + long[] left = new long[colSize], right = new long[colSize], currentRow = new long[colSize]; |
| 16 | + left[0] = prevRow[0]; |
| 17 | + for (int i = 1; i < colSize; i++) { |
| 18 | + left[i] = Math.max(left[i - 1] - 1, prevRow[i]); |
| 19 | + } |
| 20 | + right[colSize - 1] = prevRow[colSize - 1]; |
| 21 | + for (int j = colSize - 2; j >= 0; j--) { |
| 22 | + right[j] = Math.max(right[j + 1] - 1, prevRow[j]); |
| 23 | + } |
| 24 | + for (int k = 0; k < colSize; k++) { |
| 25 | + currentRow[k] = Math.max(left[k], right[k]) + points[row][k]; |
| 26 | + } |
| 27 | + prevRow = currentRow; |
| 28 | + } |
| 29 | + long max = 0; |
| 30 | + for (int i = 0; i < colSize; i++) { |
| 31 | + max = Math.max(prevRow[i], max); |
| 32 | + } |
| 33 | + return max; |
| 34 | + } |
| 35 | + |
| 36 | + // Test |
| 37 | + public static void main(String[] args) { |
| 38 | + MaximumNumberOfPointsWithCost solution = new MaximumNumberOfPointsWithCost(); |
| 39 | + |
| 40 | + int[][] input = { |
| 41 | + {1, 2, 3}, |
| 42 | + {1, 5, 1}, |
| 43 | + {3, 1, 1} |
| 44 | + }; |
| 45 | + long expectedOutput = 9; |
| 46 | + long actualOutput = solution.maxPoints(input); |
| 47 | + |
| 48 | + System.out.println("Test passed? " + (expectedOutput == actualOutput)); |
| 49 | + } |
| 50 | +} |
0 commit comments