Monday, 13 November 2023

// Program to convert recursive fibonacci into dp

// tc= O(n)

// sc= O(n) + O(n) = stack space + extra array space respectively


import java.util.*;

public class dp {

    public static int func(int n, int[] dp)

    {

         if(n<=1) return n; //base case

         if(dp[n] != -1) return dp[n]; //memoization

         return dp[n]= func(n-1,dp) + func(n-2,dp); //compute

    }

    public static void main(String[] args) {

        int n = 5;

        int dp[] = new int[n+1];

        Arrays.fill(dp,-1); // initialise all with -1

        for (int i : dp) {

            System.out.print(i+" "); // output is -1,-1,-1,-1,-1,-1

        }

        System.out.println();

        System.out.println("----");

        System.out.println(func(n,dp)); // output is 5

        System.out.println("----");

         for (int i : dp) {

            System.out.print(i+" "); // output is: -1,-1,1,2,3,5

        }

    }

}


No comments:

Post a Comment

Good thoughtful question on Binary search on answers

Problem link:  https://leetcode.com/problems/maximize-score-of-numbers-in-ranges/description/ Solution: //import java.util.Arrays; class So...