Jay works for support project where he has to resolve some tickets each day (denoted by A[i]). He knows, ahead of time, the number of tickets for each day for N days. Let A be an array of length N. Each element A[i] (where i=1 to i=N) denotes number of tickets to resolve on ith day. Jay is struggling to balance his work life. On some days, workload is huge and on other days, it is very little. Now he can procrastinate and choose to postpone up to K tickets to next day. However, tickets can only be postponed once. (Refer example 2 for more clarity). Find optimal solution where workload can be distributed as evenly as possible with above constraints and print the maximum number of tickets he needs to resolve on given days. Constraints 1<= T <= 50 1<= N <= 100 1<= K <= 100 1<= A[i] <= 10^9 Input Format First line is integer T denoting number of test cases. For each test case: First line is N K described above Next line is N spaced integers denoting number of tickets for each day Output For each test case, print a single integer per line denoting maximum number of tickets Jay needs to resolve after optimal rearrangement with above constraints.
Answers
Answer:
Given an array of size n, find all elements in array that appear more than n/k times. For example, if the input arrays is {3, 1, 2, 2, 1, 2, 3, 3} and k is 4, then the output should be [2, 3]. Note that size of array is 8 (or n = 8), so we need to find all elements that appear more than 2 (or 8/4) times. There are two elements that appear more than two times, 2 and 3.
Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.
A simple method is to pick all elements one by one. For every picked element, count its occurrences by traversing the array, if count becomes more than n/k, then print the element. Time Complexity of this method would be O(n2).
A better solution is to use sorting. First, sort all elements using a O(nLogn) algorithm. Once the array is sorted, we can find all required elements in a linear scan of array. So overall time complexity of this method is O(nLogn) + O(n) which is O(nLogn).
Following is an interesting O(nk) solution:
We can solve the above problem in O(nk) time using O(k-1) extra space. Note that there can never be more than k-1 elements in output (Why?). There are mainly three steps in this algorithm.
1) Create a temporary array of size (k-1) to store elements and their counts (The output elements are going to be among these k-1 elements). Following is structure of temporary array elements.