# Heaps are BETTER than sorting

## Метаданные

- **Канал:** NeetCode
- **YouTube:** https://www.youtube.com/watch?v=f6slNG5_1VU
- **Просмотры:** 102,637

## Описание

🚀 https://neetcode.io/ - Get lifetime access to every course I ever create!

Checkout my second Channel:  https://www.youtube.com/@NeetCodeIO

🥷 Discord: https://discord.gg/ddjKRXPqtk
🧑‍💼 LinkedIn: https://www.linkedin.com/in/navdeep-singh-3aaa14161/
🐦 Twitter: https://twitter.com/neetcode1
📷 Instagram: https://www.instagram.com/neetcodeio/
🎵 TikTok: https://www.tiktok.com/@neetcode.io



#coding #leetcode #python

## Содержание

### [0:00](https://www.youtube.com/watch?v=f6slNG5_1VU) Segment 1 (00:00 - 01:00)

let's solve a common interview question today take gifts from the richest pile the idea is we're given an array of positive integers we want to perform an operation K times the operation involves taking the biggest number 110 calculate the square root of it and then round that number down it's going to be 10 so we can replace this with a 10 now we do it again so rinse and repeat after you do the operation exactly K times take the remaining numbers and sum them up and return the result a Brute Force approach would involve scanning through the array every single time but we can do better if we actually use a heap we can get this down to be much more efficient first we want to take the gifts and turn them into a heap we want a Max Heap unfortunately python only has a minimum Heap we can get around that by turning all of the numbers negative using a little list comprehension we can just do this and then we run the simulation at each step we will pop the number it's negative so we can change the sign it then we take the square root of N and then take the floor of it and then this is the number that we're going to push back onto the Heap and we want to make sure that number is negative so we will change it back to negative after we're done with that we can just take the sum of gifts and return that but remember we turned them negative so let's return the negative of the sum and it works beautifully if you want to learn more check out this free road map I created only on NE code.

---
*Источник: https://ekstraktznaniy.ru/video/20698*