Monday, 13 November 2023

 // Maximum Sum of Non-Adjacent Elements(Memoization)

// tc = O(n)

// sc = O(n) + O(n) --> stack space + extra dp array

import java.util.*;

public class dp {

    public static int func(int index, int arr[],int dp[])

    {

        if(index==0) return arr[index];

        if(index<0) return 0;

        if(dp[index] !=-1) return dp[index];

        int pick = func(index-2, arr,dp) + arr[index];

        int notpick = func(index-1, arr, dp) + 0;

        return dp[index] = Math.max(pick,notpick);

    }

    public static void main(String[] args) {

         int arr[] = {2,1,4,9};

         int n = 3; // or, n=arr.length

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

         Arrays.fill(dp,-1);

         System.out.println(func(n,arr,dp));

    }

}


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...