C++ Path with Maximum Average Value

C++Server Side ProgrammingProgramming

Given a 2 D matrix in this problem, and we need to find the paths having maximum average value. For the path, our source is the topmost left cell, and the destination is the bottommost right cell, for example −

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

In this problem, we are allowed to move only right or downwards. This makes our problem easier as we know we need N-1 to move to the right and N-1 moves down to reach our destination. It is the shortest valid path, so that we will develop our approach by these observations.

Approach to Find the Solution

In this approach, we need to apply dynamic programming to calculate the maximum path sum as the denominator is fixed.

Example

C++ Code for the Above Approach

#include <bits/stdc++.h>
using namespace std;
int maximumPathSum(int cost[][3], int n){ // our function that return maximum average
    int dp[n+1][n+1];
    dp[0][0] = cost[0][0];
    for (int i = 1; i < n; i++) // initializing the first column of our dp matrix
        dp[i][0] = dp[i-1][0] + cost[i][0];
    for (int j = 1; j < n; j++) // initializing the first row of our dp matrix
        dp[0][j] = dp[0][j-1] + cost[0][j];
    for (int i = 1; i < n; i++) // constructing the rest of our matrix
        for (int j = 1; j <= n; j++)
            dp[i][j] = max(dp[i-1][j],dp[i][j-1]) + cost[i][j];
    return dp[n-1][n-1]; // now we divide the maximum path sum with the number of moves
}
int main(){
   int cost[3][3] = { {1, 2, 3}, {4, 5, 6},{7, 8, 9}};// given grid
   int n = 3; // order of our matrix
   printf("%.1f", float(maximumPathSum(cost, n)) / float((2*n-1)));
   return 0;
}

Output

5.8

Explanation of the Above Code

In the above approach, we observed that the maximum moves that we take are equal to (2*n) - 1, where n is the order of our cost matrix now as we now have a fixed denominator. Hence, we need to calculate the maximum path sum. Now, this is one of the classic dp problems, and we solve it using that, and then we print our result.

Conclusion

In this tutorial, we solve a problem to find the Path with the maximum average value. We also learned the C++ program for this problem and the complete approach ( Normal) by which we solved this problem. We can write the same program in other languages such as C, java, python, and other languages. We hope you find this tutorial helpful.

raja
Updated on 25-Nov-2021 10:14:21

Advertisements