Fraudulent Activity Notifications

  • + 0 comments

    C#

    public static int activityNotifications(List<int> expenditure, int d)
    {
        var totalNotifications = 0;
        int[] frequency = new int[201]; // Create a frequency array.
    
        if (expenditure.Count > d)
        {
            for (int i = 0; i < d; ++i)
            {
                frequency[expenditure[i]]++;
            }
    
            for (int i = d; i < expenditure.Count; i++)
            {
                var median = GetMedian(frequency, d);
    
                if (expenditure[i] >= 2 * median)
                {
                    totalNotifications++;
                }
    
                frequency[expenditure[i - d]]--; // Remove element from the frequency.
                frequency[expenditure[i]]++; // Add element to the frequency.
            }
        }
    
        return totalNotifications;
    }
    
    public static double GetMedian(int[] frequency, int d)
    {
        var sum = 0;
        double median = 0;
    
        if (d % 2 == 1)
        {
            var mid = d / 2;
            for (int i = 0; i < frequency.Length; ++i)
            {
                sum += frequency[i];
                if (sum > mid)
                {
                    median = i;
                    break;
                }
            }
        }
        else
        {
            var mid1 = d / 2 - 1;
            var mid2 = d / 2;
            int median1 = -1, median2 = -1;
    
            for (int i = 0; i < frequency.Length; ++i)
            {
                sum += frequency[i];
                if (sum > mid1 && median1 == -1)
                {
                    median1 = i;
                }
                if (sum > mid2)
                {
                    median2 = i;
                    median = (median1 + median2) / 2.0;
                    break;
                }
            }
        }
    
        return median;
    }