Code Logo

Festival Coin Path Count

Published at05 Jan 2026
2D Array Hard 17 views
Like14

Given an array of coin values placed along a path, count how many coins have a value greater than the average of all coins. Return the count of above-average coins.

For example, coins [2, 4, 6, 8, 10] have average 6. Coins greater than 6 are 8 and 10 — count is 2. Coins [1, 2, 3] have average 2. Coins greater than 2 are 3 — count is 1.

This problem teaches two-pass processing: first compute the average, then count elements exceeding it. It combines summation, division, and conditional counting.

The solution first sums all elements and computes the average. Then iterates again, counting elements strictly greater than the average.

Edge cases include an empty array (return 0), all coins equal to the average (return 0), and all coins above average (return the array length).

Example Input & Output

Example 1
Input
grid = [[0,1],[0,0]]
Output
1
Explanation

Only the lower-right path remains open.

Example 2
Input
grid = [[1]]
Output
0
Explanation

The starting stall is blocked, so no path exists.

Example 3
Input
grid = [[0,0,0],[0,1,0],[0,0,0]]
Output
2
Explanation

Two routes skirt the blocked middle stall.

Algorithm Flow

Recommendation Algorithm Flow for Festival Coin Path Count

Solution Approach

Compute the average in one pass, then count above-average elements in a second pass.

function aboveAverage(arr)
  if arr is empty then return 0
  sum = 0
  for i = 0 to length(arr) - 1
    sum = sum + arr[i]
  avg = sum / length(arr)
  count = 0
  for i = 0 to length(arr) - 1
    if arr[i] > avg then count = count + 1
  return count

Handle empty array. Compute sum and average. Iterate again to count elements strictly greater than the average. Return the count.

Time complexity is O(n), space complexity is O(1).

Best Answers

java

import java.util.*;
class Solution {
    public int festival_coin_path_count(Object grid) {
        int[][] g = (int[][]) grid;
        if (g.length == 0) return 0;
        int m = g.length, n = g[0].length;
        if (g[0][0] == 1) return 0;
        long[] dp = new long[n];
        dp[0] = 1;
        long MOD = 1000000007;
        for (int r = 0; r < m; r++) {
            for (int c = 0; c < n; c++) {
                if (g[r][c] == 1) dp[c] = 0;
                else if (c > 0) dp[c] = (dp[c] + dp[c-1]) % MOD;
            }
        }
        return (int) dp[n-1];
    }
}