JAVA AC Solution with O(n) and S(1) (DP)


  • 0
    J
    public class Solution {
        public int rob(int[] num) {
            if (num.length == 0) return 0;
            if (num.length == 1) return num[0];
            
            int max, last;
            
            if (num[0] >= num[1]) {
                max = num[0];
                last = max;
            } else {
                max = num[1];
                last = num[0];
            }
            
            
            for (int i=2; i<num.length; i++) {
                if (last + num[i] > max) {
                    int tmp = max;
                    max = last + num[i];
                    last = tmp;
                } else {
                    last = max;
                }
            }
            return max;
            
        }
    }

Log in to reply
 

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