We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
importjava.util.Arrays;importjava.util.Scanner;publicclassMaximumPathSum1{publicstaticvoidmain(String[]args){Scannersc=newScanner(System.in);intt=sc.nextInt();while(t-->0){intn=sc.nextInt();// Create a 2D array to store the triangle of numbersint[][]arr=newint[n][];// Input values for each row of the arrayfor(inti=0;i<n;i++){arr[i]=newint[i+1];// Initialize the array for the current rowfor(intj=0;j<=i;j++){arr[i][j]=sc.nextInt();// Input the value for the current element}}// Call the max function and print the resultSystem.out.println(max(arr));}}publicstaticintmax(int[][]arr){intn=arr.length;int[][]dp=newint[n][20];for(int[]row:dp){Arrays.fill(row,-1);}returnrecursive(0,0,arr,n,dp);}privatestaticintrecursive(inti,intj,int[][]arr,intn,int[][]dp){if(i<0||i>=n||j<0||j>=arr[i].length){return0;}if(dp[i][j]!=-1){returndp[i][j];}intdown=arr[i][j]+recursive(i+1,j,arr,n,dp);intright=arr[i][j]+recursive(i+1,j+1,arr,n,dp);returndp[i][j]=Math.max(down,right);}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
An unexpected error occurred. Please try reloading the page. If problem persists, please contact support@hackerrank.com
Project Euler #18: Maximum path sum I
You are viewing a single comment's thread. Return to all comments →
Java solution