Detailed explanation in Java : recursive to DP


  • 0
    L

    Firstly, let us establish the recurrence relationship since that will be used for both recursive and iterative using dp. The recurrence relationship looks like:

    T(n,i) = Max of ( a[i]+T(n,i+2) , a[i+1] + T(n,i+3)).

    The recursive code based on this is:

      private static int recursive(int[] nums, int[] dp, int i)
      {
        if (i >= nums.length)
        {
          return 0;
        }
        if (nums.length == 1)
        {
          return nums[0];
        }
        if (nums.length == 2)
        {
          return Math.max(nums[0], nums[1]);
        }
        if (dp[i + 2] == -1)
        {
          dp[i + 2] = recursive(nums, dp, i + 2);
        }
        if (dp[i + 3] == -1)
        {
          dp[i + 3] = recursive(nums, dp, i + 3);
        }
        int even = nums[i] + dp[i + 2];
        int odd = (i + 1 < nums.length ? nums[i + 1] : 0) + dp[i + 3];
        int res = Math.max(even, odd);
        return res;
      }
    

    The time complexity for this looks to be linear with memoization but I will let someone more knowledgeable confirm that.

    Turning that into DP is fairly easy. This solution is O(n).

        public int rob(int[] nums) {
            if(nums.length==0) {
                return 0;
            }
       int[] dp = new int[nums.length + 3];
        if (nums.length == 1)
        {
          return nums[0];
        }
        if (nums.length == 2)
        {
          return Math.max(nums[0], nums[1]);
        }
        dp[0] = nums[0];
        dp[1] = Math.max(nums[0], nums[1]);
        int max = 0;
        for (int i = 2; i < nums.length; i++)
        {
          dp[i] = Math.max(nums[i] + dp[i - 2],
              dp[i - 1]);
          max = Math.max(max, dp[i]);
        }
        return max;
        }
    

Log in to reply
 

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