Monday, November 21, 2016

Path with maximum average value - GeeksforGeeks

Path with maximum average value - GeeksforGeeks
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 which starts from top left cell move only right or down and ends on bottom right cell. We want to find a path with maximum average over all existing paths. Average is computed as total cost divided by number of cells visited in path.

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 destination (bottom rightmost). So any path from from top left corner to bottom right corner requires 2N – 1 cells. In average value, denominator is fixed and we need to just maximize numerator. Therefore we basically need to to find 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,