// C# program to implement the approach
using System;
using System.Collections.Generic;
public class GFG
{
// Precompute for every array
static Dictionary<int,int> pre_compute(int[,] arr,
int K,
Dictionary<int,int> mp)
{
for (int i = 0; i < K; i++) {
// Size of ith row stored in n
int n = arr.GetLength(1);
if(mp.ContainsKey(arr[i,0]))
mp[arr[i,0]]= Math.Min(mp[arr[i,0]] + 1, i + 1);
else
mp.Add(arr[i,0], Math.Min(1, i + 1));
// Precomputing ith row
for (int j = 1; j < n; j++) {
arr[i,j] += arr[i,j - 1];
if(mp.ContainsKey(arr[i,j]))
mp[arr[i,j]] = Math.Min(mp[arr[i,j]] + 1, i + 1);
else
mp.Add(arr[i,j], Math.Min(1, i + 1));
}
}
return mp;
}
// Function to calculate minimum common sum
static int min_common_sum(int[,] arr,
int K)
{
Dictionary<int,int> mp = new Dictionary<int,int>();
// Function call to precompute
// every row in arr
mp = pre_compute(arr, K, mp);
for (int i = 0; i < arr.GetLength(0); i++) {
if (mp[arr[0,i]] == K)
return arr[0,i];
}
return -1;
}
// Driver code
public static void Main(String[] args)
{
int K = 3;
// All k arrays are stored using 2D vector
int[,] arr
= { { 5, 2, 4 ,0}, { 1, 4, 1, 1 }, { 2, 3,0,0 } };
int ans = min_common_sum(arr, K);
Console.Write(ans);
}
}
// This code is contributed by 29AjayKumar