Advertisement
saurav_kalsoor

Find Max Happiness - JAVA

Aug 8th, 2021
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.28 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.util.Scanner;
  4.  
  5.  
  6. public class Problem {
  7.  
  8.     public static void main(String[] args){
  9.         Scanner sc = new Scanner(System.in);
  10.         int n = sc.nextInt();
  11.         int[][] arr = new int[n][3];
  12.  
  13.         for(int i=0; i<n; i++){
  14.             for(int j=0; j < 3; j++)
  15.                 arr[i][j] = sc.nextInt();
  16.         }
  17.         System.out.println(findMaxHappiness(arr, n));
  18.  
  19.     }
  20.  
  21.     static int[][] dp = new int[1001][3];
  22.  
  23.     public static int findMaxHappiness(int[][] arr, int n){
  24.         for(int i=0; i < 1001 ; i++)
  25.             for(int j=0; j < 3; j++)
  26.                 dp[i][j] = -1;
  27.         return Math.max(fun(n, 0, arr), Math.max(fun(n, 1, arr), fun(n, 2, arr)));
  28.     }
  29.  
  30.  
  31.     public static int fun(int n, int last, int[][] arr){
  32.         if(n == 0)
  33.             return 0;
  34.  
  35.         if(dp[n][last] != -1)
  36.             return dp[n][last];
  37.  
  38.  
  39.         if(last == 0)
  40.             return dp[n][last] = Math.max(fun(n-1, 1, arr) + arr[n-1][1], fun(n-1, 2, arr) + arr[n-1][2]);
  41.         else if(last == 1)
  42.             return dp[n][last] = Math.max(fun(n-1, 0, arr) + arr[n-1][0], fun(n-1, 2, arr) + arr[n-1][2]);
  43.         else
  44.             return dp[n][last] = Math.max(fun(n-1, 0, arr) + arr[n-1][0], fun(n-1, 1, arr) + arr[n-1][1]);
  45.  
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement