// C# Program to find row-wise maximum
// element sum considering elements in
// increasing order.
using System;
class GFG {
static int N = 3;
// Function to perform given task
static int getGreatestSum(int[, ] a)
{
// Getting the maximum element from
// last row
int prev_max = 0;
for (int j = 0; j < N; j++)
if (prev_max < a[N - 1, j])
prev_max = a[N - 1, j];
// Comparing it with the elements
// of above rows
int sum = prev_max;
for (int i = N - 2; i >= 0; i--) {
// Maximum of current row.
int curr_max = -2147483648;
for (int j = 0; j < N; j++)
if (prev_max > a[i, j] && a[i, j] > curr_max)
curr_max = a[i, j];
// If we could not an element smaller
// than prev_max.
if (curr_max == -2147483648)
return -1;
prev_max = curr_max;
sum += prev_max;
}
return sum;
}
// Driver Program
public static void Main()
{
int[, ] a = { { 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 } };
Console.WriteLine(getGreatestSum(a));
int[, ] b = { { 4, 5, 6 },
{ 4, 5, 6 },
{ 4, 5, 6 } };
Console.WriteLine(getGreatestSum(b));
}
}
// This code is contributed by vt_m.