Path with maximum average value
Last Updated :
14 Mar, 2024
Given a square matrix of size N*N, where each cell is associated with a specific cost. A path is defined as a specific sequence of cells that starts from the top-left cell move only right or down and ends on bottom right cell. We want to find a path with the maximum average over all existing paths. Average is computed as total cost divided by the number of cells visited in the path.
Examples:
Input : Matrix = [1, 2, 3
4, 5, 6
7, 8, 9]
Output : 5.8
Path with maximum average is, 1 -> 4 -> 7 -> 8 -> 9
Sum of the path is 29 and average is 29/5 = 5.8
One interesting observation is, the only allowed moves are down and right, we need N-1 down moves and N-1 right moves to reach the destination (bottom rightmost). So any path from top left corner to bottom right corner requires 2N - 1 cells. In average value, the denominator is fixed and we need to just maximize numerator. Therefore we basically need to find the maximum sum path. Calculating maximum sum of path is a classic dynamic programming problem, if dp[i][j] represents maximum sum till cell (i, j) from (0, 0) then at each cell (i, j), we update dp[i][j] as below,
for all i, 1 <= i <= N
dp[i][0] = dp[i-1][0] + cost[i][0];
for all j, 1 <= j <= N
dp[0][j] = dp[0][j-1] + cost[0][j];
otherwise
dp[i][j] = max(dp[i-1][j], dp[i][j-1]) + cost[i][j];
Once we get maximum sum of all paths we will divide this sum by (2N - 1) and we will get our maximum average.
Implementation:
C++
//C/C++ program to find maximum average cost path
#include <bits/stdc++.h>
using namespace std;
// Maximum number of rows and/or columns
const int M = 100;
// method returns maximum average of all path of
// cost matrix
double maxAverageOfPath(int cost[M][M], int N)
{
int dp[N+1][N+1];
dp[0][0] = cost[0][0];
/* Initialize first column of total cost(dp) array */
for (int i = 1; i < N; i++)
dp[i][0] = dp[i-1][0] + cost[i][0];
/* Initialize first row of dp array */
for (int j = 1; j < N; j++)
dp[0][j] = dp[0][j-1] + cost[0][j];
/* Construct rest of the dp array */
for (int i = 1; i < N; i++)
for (int j = 1; j <= N; j++)
dp[i][j] = max(dp[i-1][j],
dp[i][j-1]) + cost[i][j];
// divide maximum sum by constant path
// length : (2N - 1) for getting average
return (double)dp[N-1][N-1] / (2*N-1);
}
/* Driver program to test above functions */
int main()
{
int cost[M][M] = { {1, 2, 3},
{6, 5, 4},
{7, 3, 9}
};
printf("%f", maxAverageOfPath(cost, 3));
return 0;
}
Java
// JAVA Code for Path with maximum average
// value
import java.io.*;
class GFG {
// method returns maximum average of all
// path of cost matrix
public static double maxAverageOfPath(int cost[][],
int N)
{
int dp[][] = new int[N+1][N+1];
dp[0][0] = cost[0][0];
/* Initialize first column of total cost(dp)
array */
for (int i = 1; i < N; i++)
dp[i][0] = dp[i-1][0] + cost[i][0];
/* Initialize first row of dp array */
for (int j = 1; j < N; j++)
dp[0][j] = dp[0][j-1] + cost[0][j];
/* Construct rest of the dp array */
for (int i = 1; i < N; i++)
for (int j = 1; j < N; j++)
dp[i][j] = Math.max(dp[i-1][j],
dp[i][j-1]) + cost[i][j];
// divide maximum sum by constant path
// length : (2N - 1) for getting average
return (double)dp[N-1][N-1] / (2 * N - 1);
}
/* Driver program to test above function */
public static void main(String[] args)
{
int cost[][] = {{1, 2, 3},
{6, 5, 4},
{7, 3, 9}};
System.out.println(maxAverageOfPath(cost, 3));
}
}
// This code is contributed by Arnav Kr. Mandal.
C#
// C# Code for Path with maximum average
// value
using System;
class GFG {
// method returns maximum average of all
// path of cost matrix
public static double maxAverageOfPath(int [,]cost,
int N)
{
int [,]dp = new int[N+1,N+1];
dp[0,0] = cost[0,0];
/* Initialize first column of total cost(dp)
array */
for (int i = 1; i < N; i++)
dp[i, 0] = dp[i - 1,0] + cost[i, 0];
/* Initialize first row of dp array */
for (int j = 1; j < N; j++)
dp[0, j] = dp[0,j - 1] + cost[0, j];
/* Construct rest of the dp array */
for (int i = 1; i < N; i++)
for (int j = 1; j < N; j++)
dp[i, j] = Math.Max(dp[i - 1, j],
dp[i,j - 1]) + cost[i, j];
// divide maximum sum by constant path
// length : (2N - 1) for getting average
return (double)dp[N - 1, N - 1] / (2 * N - 1);
}
// Driver Code
public static void Main()
{
int [,]cost = {{1, 2, 3},
{6, 5, 4},
{7, 3, 9}};
Console.Write(maxAverageOfPath(cost, 3));
}
}
// This code is contributed by nitin mittal.
JavaScript
<script>
// JavaScript Code for Path with maximum average value
// method returns maximum average of all
// path of cost matrix
function maxAverageOfPath(cost, N)
{
let dp = new Array(N+1);
for (let i = 0; i < N + 1; i++)
{
dp[i] = new Array(N + 1);
for (let j = 0; j < N + 1; j++)
{
dp[i][j] = 0;
}
}
dp[0][0] = cost[0][0];
/* Initialize first column of total cost(dp)
array */
for (let i = 1; i < N; i++)
dp[i][0] = dp[i-1][0] + cost[i][0];
/* Initialize first row of dp array */
for (let j = 1; j < N; j++)
dp[0][j] = dp[0][j-1] + cost[0][j];
/* Construct rest of the dp array */
for (let i = 1; i < N; i++)
for (let j = 1; j < N; j++)
dp[i][j] = Math.max(dp[i-1][j],
dp[i][j-1]) + cost[i][j];
// divide maximum sum by constant path
// length : (2N - 1) for getting average
return dp[N-1][N-1] / (2 * N - 1);
}
let cost = [[1, 2, 3],
[6, 5, 4],
[7, 3, 9]];
document.write(maxAverageOfPath(cost, 3));
</script>
PHP
<?php
// Php program to find maximum average cost path
// method returns maximum average of all path of
// cost matrix
function maxAverageOfPath($cost, $N)
{
$dp = array(array()) ;
$dp[0][0] = $cost[0][0];
/* Initialize first column of total cost(dp) array */
for ($i = 1; $i < $N; $i++)
$dp[$i][0] = $dp[$i-1][0] + $cost[$i][0];
/* Initialize first row of dp array */
for ($j = 1; $j < $N; $j++)
$dp[0][$j] = $dp[0][$j-1] + $cost[0][$j];
/* Construct rest of the dp array */
for ($i = 1; $i < $N; $i++)
{
for ($j = 1; $j <= $N; $j++)
$dp[$i][$j] = max($dp[$i-1][$j],$dp[$i][$j-1]) + $cost[$i][$j];
}
// divide maximum sum by constant path
// length : (2N - 1) for getting average
return $dp[$N-1][$N-1] / (2*$N-1);
}
// Driver code
$cost = array(array(1, 2, 3),
array( 6, 5, 4),
array(7, 3, 9) ) ;
echo maxAverageOfPath($cost, 3) ;
// This code is contributed by Ryuga
?>
Python3
# Python program to find
# maximum average cost path
# Maximum number of rows
# and/or columns
M = 100
# method returns maximum average of
# all path of cost matrix
def maxAverageOfPath(cost, N):
dp = [[0 for i in range(N + 1)] for j in range(N + 1)]
dp[0][0] = cost[0][0]
# Initialize first column of total cost(dp) array
for i in range(1, N):
dp[i][0] = dp[i - 1][0] + cost[i][0]
# Initialize first row of dp array
for j in range(1, N):
dp[0][j] = dp[0][j - 1] + cost[0][j]
# Construct rest of the dp array
for i in range(1, N):
for j in range(1, N):
dp[i][j] = max(dp[i - 1][j],
dp[i][j - 1]) + cost[i][j]
# divide maximum sum by constant path
# length : (2N - 1) for getting average
return dp[N - 1][N - 1] / (2 * N - 1)
# Driver program to test above function
cost = [[1, 2, 3],
[6, 5, 4],
[7, 3, 9]]
print(maxAverageOfPath(cost, 3))
# This code is contributed by Soumen Ghosh.
Time complexity: O(N2) for given input N
Auxiliary Space: O(N2) for given input N.
Method - 2: Without using Extra N*N space
We can use input cost array as a dp to store the ans. so this way we don't need an extra dp array or no that extra space.\
One observation is that the only allowed moves are down and right, we need N-1 down moves and N-1 right moves to reach the destination (bottom rightmost). So any path from top left corner to bottom right corner requires 2N - 1 cell. In average value, the denominator is fixed and we need to just maximize numerator. Therefore we basically need to find the maximum sum path. Calculating maximum sum of path is a classic dynamic programming problem, also we don't need any prev cost[i][j] value after calculating dp[i][j] so we can modifies the cost[i][j] value such that we don't need extra space for dp[i][j].
for all i, 1 <= i < N
cost[i][0] = cost[i-1][0] + cost[i][0];
for all j, 1 <= j < N
cost[0][j] = cost[0][j-1] + cost[0][j];
otherwise
cost[i][j] = max(cost[i-1][j], cost[i][j-1]) + cost[i][j];
Below is the implementation of the above approach:
C++
// C++ program to find maximum average cost path
#include <bits/stdc++.h>
using namespace std;
// Method returns maximum average of all path of cost matrix
double maxAverageOfPath(vector<vector<int>>cost)
{
int N = cost.size();
// Initialize first column of total cost array
for (int i = 1; i < N; i++)
cost[i][0] = cost[i][0] + cost[i - 1][0];
// Initialize first row of array
for (int j = 1; j < N; j++)
cost[0][j] = cost[0][j - 1] + cost[0][j];
// Construct rest of the array
for (int i = 1; i < N; i++)
for (int j = 1; j <= N; j++)
cost[i][j] = max(cost[i - 1][j], cost[i][j - 1]) + cost[i][j];
// divide maximum sum by constant path
// length : (2N - 1) for getting average
return (double)cost[N - 1][N - 1] / (2 * N - 1);
}
// Driver program
int main()
{
vector<vector<int>> cost = {{1, 2, 3},
{6, 5, 4},
{7, 3, 9}
};
cout << maxAverageOfPath(cost);
return 0;
}
Java
// Java program to find maximum average cost path
import java.io.*;
class GFG {
// Method returns maximum average of all path of cost
// matrix
static double maxAverageOfPath(int[][] cost)
{
int N = cost.length;
// Initialize first column of total cost array
for (int i = 1; i < N; i++)
cost[i][0] = cost[i][0] + cost[i - 1][0];
// Initialize first row of array
for (int j = 1; j < N; j++)
cost[0][j] = cost[0][j - 1] + cost[0][j];
// Construct rest of the array
for (int i = 1; i < N; i++)
for (int j = 1; j < N; j++)
cost[i][j] = Math.max(cost[i - 1][j],
cost[i][j - 1])
+ cost[i][j];
// divide maximum sum by constant path
// length : (2N - 1) for getting average
return (double)cost[N - 1][N - 1] / (2 * N - 1);
}
// Driver program
public static void main(String[] args)
{
int[][] cost
= { { 1, 2, 3 }, { 6, 5, 4 }, { 7, 3, 9 } };
System.out.println(maxAverageOfPath(cost));
}
}
// This code is contributed by karandeep1234
C#
// C# program to find maximum average cost path
using System;
class GFG {
// Method returns maximum average of all path of cost
// matrix
static double maxAverageOfPath(int[, ] cost)
{
int N = cost.GetLength(0);
// Initialize first column of total cost array
for (int i = 1; i < N; i++)
cost[i, 0] = cost[i, 0] + cost[i - 1, 0];
// Initialize first row of array
for (int j = 1; j < N; j++)
cost[0, j] = cost[0, j - 1] + cost[0, j];
// Construct rest of the array
for (int i = 1; i < N; i++)
for (int j = 1; j < N; j++)
cost[i, j] = Math.Max(cost[i - 1, j],
cost[i, j - 1])
+ cost[i, j];
// divide maximum sum by constant path
// length : (2N - 1) for getting average
return (double)cost[N - 1, N - 1] / (2 * N - 1);
}
// Driver program
static void Main(string[] args)
{
int[, ] cost
= { { 1, 2, 3 }, { 6, 5, 4 }, { 7, 3, 9 } };
Console.WriteLine(maxAverageOfPath(cost));
}
}
// This code is contributed by karandeep1234
JavaScript
// Method returns maximum average of all path of cost matrix
function maxAverageOfPath(cost)
{
let N = cost.length;
// Initialize first column of total cost array
for (let i = 1; i < N; i++)
cost[i][0] = cost[i][0] + cost[i - 1][0];
// Initialize first row of array
for (let j = 1; j < N; j++)
cost[0][j] = cost[0][j - 1] + cost[0][j];
// Construct rest of the array
for (let i = 1; i < N; i++)
for (let j = 1; j <= N; j++)
cost[i][j] = Math.max(cost[i - 1][j], cost[i][j - 1]) + cost[i][j];
// divide maximum sum by constant path
// length : (2N - 1) for getting average
return (cost[N - 1][N - 1]) / (2.0 * N - 1);
}
// Driver program
let cost = [[1, 2, 3],
[6, 5, 4],
[7, 3, 9]];
console.log(maxAverageOfPath(cost))
// This code is contributed by karandeep1234.
Python3
# Python program to find maximum average cost path
from typing import List
def maxAverageOfPath(cost: List[List[int]]) -> float:
N = len(cost)
# Initialize first column of total cost array
for i in range(1, N):
cost[i][0] = cost[i][0] + cost[i - 1][0]
# Initialize first row of array
for j in range(1, N):
cost[0][j] = cost[0][j - 1] + cost[0][j]
# Construct rest of the array
for i in range(1, N):
for j in range(1, N):
cost[i][j] = max(cost[i - 1][j], cost[i][j - 1]) + cost[i][j]
# divide maximum sum by constant path
# length : (2N - 1) for getting average
return cost[N - 1][N - 1] / (2 * N - 1)
# Driver program
def main():
cost = [[1, 2, 3],
[6, 5, 4],
[7, 3, 9]]
print(maxAverageOfPath(cost))
if __name__ == '__main__':
main()
Time Complexity: O(N*N)
Auxiliary Space: O(1)
Similar Reads
Longest Sub-array with maximum average value Given an array arr[] of n integers. The task is to find the maximum length of the sub-array which has the maximum average value (average of the elements of the sub-array). Examples: Input: arr[] = {2, 3, 4, 5, 6} Output: 1 {6} is the required sub-arrayInput: arr[] = {6, 1, 6, 6, 0} Output: 2 {6} and
6 min read
Maximum Edges In The Path Given a directed graph with n nodes and m edges. Each edge is assigned a weight. The graph can also be disconnected and there might be multiple edges and self-loops. The task is to choose a path such that the weights of the edges are in strictly increasing order and the path has the maximum possible
10 min read
Maximum average good ratio Given an array of chocolates, each represented by a pair[good_i, total_i], where good_i is the count of eatable (good) chocolates and total_i is the total count of chocolates of that type. Additionally, you have a set of extra chocolates that can be added to any type of chocolate. The goal is to str
8 min read
Longest Path with Maximum Letter Frequency Given a graph with n vertex and m-directed edges. One lowercase letter is assigned to each vertex. The value of the path is the number of the most frequently occurring letters in the path. The task is to find a path whose value is the largest. Example: Input: n = 5, m = 4, node_value = "abaca", edge
9 min read
Maximum Path sum in a N-ary Tree Given an undirected tree with n nodes numbered from 1 to n and an array arr[] where arr[i] denotes the value assigned to (i+1)th node. The connections between the nodes are provided in a 2-dimensional array edges[][]. The task is to find the maximum path sum between any two nodes. (Both the nodes ca
7 min read
Maximum path sum in matrix Given a matrix of size n * m. Find the maximum path sum in the matrix. The maximum path is the sum of all elements from the first row to the last row where you are allowed to move only down or diagonally to left or right. You can start from any element in the first row.Examples: Input: mat[][] = 10
6 min read
Find Maximum Average Marks in Student Pairs Given an array A[] containing N pairs in the form of (X, Y). Where X and Y denote the student's name and marks respectively. Then your task is to output the maximum average marks of a student. Examples: Input: A[] = {{"Bob", "87"}, {"Mike", "35"}, {"Bob", "52"}, {"Jason", "35"}, {"Mike", "55"}, {"Je
8 min read
Maximum Path Sum in a Binary Tree Given a binary tree, the task is to find the maximum path sum. The path may start and end at any node in the tree.Example: Input: Output: 42Explanation: Max path sum is represented using green colour nodes in the above binary tree.Input: Output: 31Explanation: Max path sum is represented using green
8 min read
Find the maximum sum path in the given Matrix Consider an infinite matrix. The cells of the matrix are filled with natural numbers from the cell (1, 1) in the direction of top right to bottom left diagonally. Then the task is to output the Maximum path sum between two points (X1, Y1) and (X2, Y2). Matrix filling process is as follows: Matrix fi
7 min read
Maximum average sum partition of an array Given an array, we partition a row of numbers A into at most K adjacent (non-empty) groups, then the score is the sum of the average of each group. What is the maximum score that can be scored? Examples: Input : A = { 9, 1, 2, 3, 9 } K = 3 Output : 20 Explanation : We can partition A into [9], [1, 2
10 min read