DP with Java 8 Stream


  • 0
    X
    public int minCost(int[][] costs) {
        if (costs == null || costs.length == 0) {
            return 0;
        }
    
        int[] minCosts = Arrays.stream(costs).reduce(new int[3], (res, c) -> {
            int[] cur = res.clone();
            res[0] = Math.min(cur[1], cur[2]) + c[0];
            res[1] = Math.min(cur[0], cur[2]) + c[1];
            res[2] = Math.min(cur[0], cur[1]) + c[2];
            return res;
        });
    
        return Math.min(Math.min(minCosts[0], minCosts[1]), minCosts[2]);
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.