O(n) iterative Java Solution


  • 0
    C
    public class Solution {
        public int rob(int[] num) {
            int[] currentSum = new int[num.length + 1];
            if(num.length == 0) return 0;
            if(num.length == 1) return num[0];
            if(num.length == 2) return Math.max(num[0], num[1]);
            currentSum[0] = 0;
            currentSum[1] = num[0];
            
            int i = 2;
            while(i <= num.length ){
                currentSum[i] = Math.max(currentSum[i - 1], currentSum[i - 2] + num[i-1]);
                i++;
            }
            return currentSum[num.length];
        }
    }
    

    Very straight forward DP solution, not that clean, so any suggestions?


Log in to reply
 

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