Rewrite the solution

  • 0

    Re: [Java O(n) solution](space O(1))
    @tusizi : Your solution is awesome! I just made a few change to make it easy to understand.

    public class Solution {
        public int rob(int[] nums) {
            int prevNo = 0;     // max money can get if NOT rob previous house
            int prevYes = 0;    // max money can get if rob previous house
            for (int n : nums) {
                //1.Rob the current house
                int currYes =  prevNo + n;  //previous not robbed + current house
                //2.Don't rob
                int currNo = Math.max(prevNo, prevYes); //Max of the previous cell robbed and not robbed -- Optimal substructure.
                //Update values for the next round
                prevNo = currNo;
                prevYes = currYes;
            return Math.max(prevNo, prevYes);

Log in to reply

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