Last active
October 19, 2019 12:40
-
-
Save kkabdol/9680a88a0f524efad2f363e7f92dceef to your computer and use it in GitHub Desktop.
Fraudulent Activity Notifications
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// problem : https://www.hackerrank.com/challenges/fraudulent-activity-notifications/problem | |
int activityNotifications(vector<int> expenditure, int d) { | |
const int MAX_EXPENSE = 200; | |
const bool isEven = ( d % 2 ) == 0; | |
const int medianIndex = isEven ? ( d / 2 ) - 1 : d / 2; | |
// setup counting sort | |
vector<int> expenditureCounter( MAX_EXPENSE + 1, 0 ); | |
for( int j = 0; j < d; ++j ) | |
{ | |
++expenditureCounter[ expenditure[ i - d + j ] ]; | |
} | |
for( int j = 0; j <= MAX_EXPENSE; ++j ) | |
{ | |
expenditureCounter[ j + 1 ] += expenditureCounter[ j ]; | |
} | |
int notifyCount = 0; | |
for( int i = d; i < expenditure.size(); ++i ) | |
{ | |
// find median | |
double median = 0.0; | |
for( int j = 0; j <= MAX_EXPENSE; ++j ) | |
{ | |
if( expenditureCounter[ j ] > medianIndex ) | |
{ | |
median = static_cast<double>( j ); | |
break; | |
} | |
} | |
if( isEven ) | |
{ | |
// find another median | |
for( int j = 0; j <= MAX_EXPENSE; ++j ) | |
{ | |
if( expenditureCounter[ j ] > ( medianIndex + 1 ) ) | |
{ | |
median = ( median + static_cast<double>( j ) ) / 2.0; | |
break; | |
} | |
} | |
} | |
// check if it needs to notify | |
if( median * 2.0 <= expenditure[ i ] ) | |
{ | |
++notifyCount; | |
} | |
// remove oldest expenditure from trail | |
for( int j = expenditure[ i - d ]; j <= MAX_EXPENSE; ++j ) | |
{ | |
--expenditureCounter[ j ]; | |
} | |
// add today | |
for( int j = expenditure[ i ]; j <= MAX_EXPENSE; ++j ) | |
{ | |
++expenditureCounter[ j ]; | |
} | |
} | |
return notifyCount; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment