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.
public class MaximumPathSum1
{
public static void Main(string[] args)
{
int t = int.Parse(Console.ReadLine());
while (t-- > 0)
{
int n = int.Parse(Console.ReadLine());
int[][] arr = new int[n][];
// Input values for each row of the array
for (int i = 0; i < n; i++)
{
arr[i] = new int[i + 1]; // Initialize the array for the current row
string[] values = Console.ReadLine().Split(' ');
for (int j = 0; j <= i; j++)
{
arr[i][j] = int.Parse(values[j]); // Input the value for the current element
}
}
// Call the max function and print the result
Console.WriteLine(Max(arr));
}
}
public static int Max(int[][] arr)
{
int n = arr.Length;
int[][] dp = new int[n][];
for (int i = 0; i < n; i++)
{
dp[i] = new int[i + 1];
for (int j = 0; j <= i; j++)
{
dp[i][j] = -1;
}
}
return Recursive(0, 0, arr, n, dp);
}
private static int Recursive(int i, int j, int[][] arr, int n, int[][] dp)
{
if (i < 0 || i >= n || j < 0 || j >= arr[i].Length)
{
return 0;
}
if (dp[i][j] != -1)
{
return dp[i][j];
}
int down = arr[i][j] + Recursive(i + 1, j, arr, n, dp);
int right = arr[i][j] + Recursive(i + 1, j + 1, arr, n, dp);
return dp[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 →
In C#:
using System;
public class MaximumPathSum1 { public static void Main(string[] args) { int t = int.Parse(Console.ReadLine());
}