Fraudulent Activity Notifications

  • + 0 comments

    Java 8 Solution

    public static int activityNotifications(List<Integer> expenditure, int d){
            final int size = expenditure.size();
            if(d>=size){
                return 0;
            }
            
            int notifications = 0;
            List<Integer> dList =  expenditure.subList(0,d).stream().sorted().collect(Collectors.toList());
            for(int i=d; i<size; i++){
                int doubledMedian = getDoubledMedian(dList);
                int current = expenditure.get(i);
                if(current >= doubledMedian){
                    notifications++;
                }
                Integer firstDay = expenditure.get(i-d);
                dList.remove(firstDay);
                addItemToSortedList(dList, current);
                firstDay = current;  
            }
            return notifications;
        }
        
        final static int getDoubledMedian(List<Integer> sortedList){
            final int size = sortedList.size();
            final int index = size/2;
            if(size%2 != 0){
                return 2*sortedList.get(index);
            }
            return sortedList.get(index-1) + sortedList.get(index);
        }
        
        final static void addItemToSortedList(List<Integer> dList, int newItem){
            int index = Collections.binarySearch(dList, newItem);
            if(index < 0){
                dList.add(-(index+1),newItem);
                return;
            }
            dList.add(index,newItem);
        }