PROBLEM LINK:Setter: Aakash Jaiswal Tester: Deepansh Parmani Editorialist: Akash Bhalotia DIFFICULTY:CAKEWALK PREREQUISITES:PROBLEM:Given an array of size N, find the sum of the K largest elements of the array. QUICK EXPLANATION:Sort the array in nondecreasing or ascending order. Find the sum of the last K elements. EXPLANATION:One of the simplest ways to solve this problem is to use Sorting. As 1 $\leq$ N $\leq$ 2* $10^5$, O($N^2$) sorting algorithms like Bubble Sort, Selection Sort, Insertion Sort, etc. would result in Time Limit Exceeded (TLE). Thus we have to use faster sorting algorithms like Merge Sort, Quick Sort, Heap Sort, etc. which generally result in a time complexity of O(NlogN). In CP (Competitive Programming), one doesn't generally implement the full sorting algorithm, but uses inbuilt library sorting function of the language; For Example: 1) Sort the array in ascending order. Now the Klargest elements are all populated towards the end of the array, from index (NK+1) to index N, 1based indexing. 2) Using a loop, you can find the sum of the last K elements of this sorted array. A 32bit integer datatype should be sufficient to store the sum, as $1\leq a[i]\leq 10^4$ and $1\leq K \leq 20$. Another way to solve this problem, using sorting, is to sort the array in descending order and find the sum of the first K elements in it. COMPLEXITY:Time complexity: O(NlogN) per test case Space Complexity: O(N) SOLUTIONS:Similar Problem:Find the sum of the Ksmallest elements of the array. Same constraints. =============================================== ALTERNATIVE SOLUTION:1) O(N*K) using Looping: 2) O(N*logK) using a MinHeap: USEFUL READUPS AND TUTORIALS:Don't know a topic? No worries :) You'll find the links below useful. =============================================== BONUS:Can we solve this problem in O(N) time? ================================================================================================== Feel free to share your approach if it differs. If you have any doubts or you feel stuck at any point, feel free to ask them below. You can also reach me at $akashbhalotia\.unofficial@gmail\.com$ . I tried my best to make the editorial beginnerfriendly. Suggestions are always welcomed :)
This question is marked "community wiki".
asked 26 Aug '18, 14:55
