Grokking Data Structures & Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Time complexity for final summation

Jimmy

Feb 6, 2024

Why is the time complexity for the final summation portion O(N)? Shouldn't it be O(N log N) since you are popping all gifts off of the heap to calculate the sum? This seems like an unnecessary step since you don't need a particular ordering of the gifts when calculating the sum - you just need to know how many gifts are remaining.

A more optimized solution would be to get the total number of gifts at the start and deduct the number of gifts taken after each second.

#include <iostream> #include <vector> #include <queue> #include <cmath> #include <numeric> class Solution { public: int remainingGifts(std::vector<int>& gifts, int k) { // ToDo: Write Your Code Here. int result = std::accumulate(gifts.begin(), gifts.end(), 0); std::priority_queue pq(gifts.begin(), gifts.end()); for (int i = 0; i < k; i++) { int mostGifts = pq.top(); pq.pop(); int leaveGifts = std::sqrt(mostGifts); pq.push(leaveGifts); result -= (mostGifts - leaveGifts); } return result; } };

1

0

Comments
Comments
Pavel Kostenko
Pavel Kostenko10 months ago

Great observation! 👍 I was also concernted with O(n log n) complexity to sum up the values.

On this page