Fraudulent Activity Notifications

  • + 0 comments

    Here is a Java solution with sorted arrayList and sliding window:

    public static int activityNotifications(List<Integer> expenditure, int d) {
            var list = new ArrayList<Integer>();
            int notifications = 0;
    
            Function<List<Integer>, Double> medFunc;
            if (d % 2 == 0) {
                medFunc = (arr) -> ((arr.get(d / 2) + arr.get(d / 2 - 1)) / 2.);
            } else {
                medFunc = (arr) -> (double) arr.get(d / 2);
            }
    
            var indexToRemove = 0;
            for (var i = 0; i < expenditure.size(); i++) {
                if (i < d) {
                    add(expenditure.get(i), list);
                } else {
                    double med = medFunc.apply(list);
                    if (med * 2 <= expenditure.get(i)) {
                        notifications++;
                    }
    
                    if (i < expenditure.size() - 1) {
                        add(expenditure.get(i), list);
                        remove(expenditure.get(indexToRemove), list);
                        indexToRemove++;
                    }
                }
            }
    
            return notifications;
        }
    
        public static void add(Integer value, List<Integer> list) {
            int index = Collections.binarySearch(list, value);
    
            // If value is not found, binarySearch returns (-(insertion point) - 1)
            if (index < 0) {
                index = -(index + 1);
            }
    
            list.add(index, value);
        }
    
        public static void remove(Integer value, List<Integer> list) {
            int index = Collections.binarySearch(list, value);
            if (index >= 0) {
                list.remove(index);
            }
        }