Sunday, July 17, 2022

Frequency of Max Value | C# | HackerRank

public static List<int> FrequencyOfMaxValue(List<int> numbers,
    List<int> q)
{
    List<int> result = new List<int>();
    int n = numbers.Count;
    int[,] table = new int[2,n];
    Dictionary<int, int> counts = new Dictionary<int, int>();
    table[0,n-1] = numbers[n-1];
    table[1,n-1] = 1;
    counts.Add(numbers[n-1], 1);
    for(int i = n-2; i >= 0; i--)
    {
        if(!counts.ContainsKey(numbers[i]))
            counts.Add(numbers[i],1);
        else
            counts[numbers[i]]++;

        if(numbers[i] > table[0, i+1])
        {
            table[0,i] = numbers[i];
            table[1,i] = 1;
        }
        else
        {
            table[0,i] = table[0, i+1];
            table[1,i] = counts[table[0,i]];
        }
    }
    for(int i = 0; i < n; i++)
    {
        result.Add(table[1,q[i] - 1]);
    }
    return result;
} 

No comments:

Post a Comment

horizontal ads