The function must return the count of pairs of numbers in the array songs (integer array consisting of lengths of songs in seconds) such that the pairs formed add up to whole minutes.
long playlist(int songs_count, int *songs) {
int i, j, k = 0;
for (i = 0; i < songs_count; i++) {
for (j = i + 1; j < songs_count; j++)
if ((songs[i] + songs[j]) % 60 == 0)
k++;
}
return k;
}
A first straight forward approach would be like this:
seconds%60initialized to all zeroes.a = array[i]songs andb = array[60-i]matching songs which you need to combine:num = a*b; k += num;i==0andi==30you need special handling as the matching song is in same array element:num = a*(a-1);This will reduce the time complexity to O(N):
You need
nto populate the array (could be done once when building the song list) and0..30for the calculation.This results in
O(N)+O(1)Edit: Depending on your rules (does order of the songs matter) you might need to multiply with 2.