Approach
Sorting and greedy selection
For Minimum Falling Path Sum II, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 28 lines of Java from the credited upstream file 1289.java.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int minFallingPathSum(int[][] grid) {3 final int n = grid.length;4 5 for (int i = 1; i < n; ++i) {6 Pair<Integer, Integer>[] twoMinNumAndIndexes = getTwoMinNumAndIndexes(grid[i - 1]);7 final int firstMinNum = twoMinNumAndIndexes[0].getKey();8 final int firstMinIndex = twoMinNumAndIndexes[0].getValue();9 final int secondMinNum = twoMinNumAndIndexes[1].getKey();10 for (int j = 0; j < n; ++j)11 if (j == firstMinIndex)12 grid[i][j] += secondMinNum;13 else14 grid[i][j] += firstMinNum;15 }16 17 return Arrays.stream(grid[n - 1]).min().getAsInt();18 }19 20 private Pair<Integer, Integer>[] getTwoMinNumAndIndexes(int[] arr) {21 List<Pair<Integer, Integer>> numAndIndexes = new ArrayList<>();22 for (int i = 0; i < arr.length; ++i)23 numAndIndexes.add(new Pair<>(arr[i], i));24 Collections.sort(numAndIndexes, Comparator.comparingInt(Pair::getKey));25 return new Pair[] {numAndIndexes.get(0), numAndIndexes.get(1)};26 }27}28