Dynamic Programming 05
Stickler the thief wants to loot money from a society having n houses in a single line. He is a weird person and follows a certain rule when looting the houses. According to the rule, he will never loot two consecutive houses. At the same time, he wants to maximize the amount he loots. The thief knows which house has what amount of money but is unable to come up with an optimal looting strategy. He asks for your help to find the maximum money he can get if he strictly follows the rule. Each house has a[i]amount of money present in it.
Problem link :- click here
Code
import java.util.Scanner;
// STICKLER THIEF
public class DynamicProgramming_05
{
// Recursion and memoization
static int maxLoot(int arr[], int start, int memo[])
{
if(start >= arr.length)
return 0;
if(memo[start] != 0)
return memo[start];
int withFirstEle = arr[start] + maxLoot(arr, start+2, memo);
int withoutFirstEle = maxLoot(arr, start+1, memo);
int ans = Math.max(withFirstEle, withoutFirstEle);
memo[start] = ans;
return ans;
}
// Dynamic programming
static int maxLoot2(int arr[])
{
int n = arr.length;
int maxLoot[] = new int[n];
maxLoot[n-1] = arr[n-1];
maxLoot[n-2] = Math.max(arr[n-2], arr[n-1]);
for(int i=n-3; i>=0; i--)
maxLoot[i] = Math.max(maxLoot[i+1], arr[i] + maxLoot[i+2]);
return maxLoot[0];
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter the size of the array : ");
int n = s.nextInt();
int arr[] = new int[n];
System.out.println("Enter the array elements : ");
for(int i=0; i<n; i++)
arr[i] = s.nextInt();
int memo[] = new int[n+1];
int ans = maxLoot(arr, 0, memo);
System.out.println(ans);
int ans2 = maxLoot2(arr);
System.out.println(ans2);
s.close();
}
}
Comments
Post a Comment