Project Euler #18: Maximum path sum I

  • + 0 comments

    In C#:

    using System;

    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);
    }
    

    }