Link to the problem: http://codeforces.com/problemset/problem/958/F2

I thought of doing it, this way: We need to find the smallest length subarray which has each light-saber either greater or equal to the requirement, then minimum deletion will be equal to the sum of extra light-saber of each type.

To implement this I thought of maintaining a prefix-sum array for each of the m light-saber, then using the prefix sum array and binary search we can find the "the smallest length subarray which has which has each light-saber either greater or equal to the requirement. However the time complexity of this solution will be O(M * N * log(N)) which will Time-Out for the given constraint.

What can be an optimal solution?