Minimize Maximum of Array - Leetcode 2439 - Python

NeetCodeIO · Intermediate ·⚡ Algorithms & Data Structures ·3y ago

Key Takeaways

Solves Leetcode 2439, Minimize Maximum of Array, using Python and array manipulation

Full Transcript

hey everyone welcome back and let's write some more neat code today so today let's solve the problem minimize maximum of array this is a pretty tricky problem especially for a medium if you couldn't solve it definitely don't get discouraged we're given a zero indexed array where every integer is going to be non-negative so basically zero or greater than zero the way they describe this problem is that there are like a few operations that we can do I'll go through these but then I'll kind of explain a better way to think about this problem like a more simple way so I'll just use the same example that they do in this problem what we can do is choose any integer except the leftmost one and you'll see why in just a second so among any of these integers we are going to pick one of them suppose it's this guy we're going to decrement it by one minus one so this is now going to be six and we take that one that we decremented and actually move it over to the left over here so this is going to be plus one now four now since we can't decrement this the reason we can't decrement this is because where would the value go if we say this is 2 now that one is kind of lost that's not something we're allowed to do and given these operations we just want to return the minimum possible value of the maximum integer of nums after performing any number of operations so that's the simple part we can perform this operation any time we want like an infinite number of times if we want this part you'll probably have to read a few times to understand what exactly it's saying basically in this array we're always going to return the maximum value in this case it's seven but what we're trying to do is minimize that maximum value so one way to do it would be to do exactly what we did make this a six and make this a four now the maximum is six well it's in two spots but it's still six so that's what we would return but we can actually do better you can see in the output over here the result is actually five how exactly would we get to to that point well you kind of have to prioritize by taking the maximums and decreasing them as you would guess by decreasing this we're not going to get anywhere so for this guy let's decrement it one more time let's now say it's going to be a five I'll write it down over here and this guy is now going to be a five we took two from here and moved it to the left now our maximum is still six but we can make this a five and make this a two at this point we can't really do anything we could definitely get this smaller and we could probably get this smaller but this is going to be our bottleneck it's basically going to keep growing or the best we can do is just leave it as it is so in this case we return five now based on that kind of quick walkthrough you might think that we could go with like a Max Heap approach where we just take from this entire array and get the maximum value so that we can decrement it and try to lower the overall maximum if you try doing it this way you'll see it's pretty tricky and even if we could get it to work Arc the overall time complexity would be higher than the solution I'm about to show you and using a Max Heap how would we even know that we're done that's kind of the complicated part so there is a better way to do this and it has to do with a kind of again simplifying this problem first of all let's make an observation we know that the result can't possibly be smaller than the initial value in this spot because this value is never going to get any smaller it's possible that everything over here is smaller than this but we're returning the maximum remember so that's something to keep in mind this is initially going to be our result and now just going down this track of thinking let's see if we can arrive to A solution just by iterating through the array the reason we're going to start from left to right one is because that's what we usually do but also because we're kind of thinking of it in terms of sub problems what is the result of this subarray what's the minimize maximum of this subarray and then we can EXP ban that what's the result of this subarray and kind of keep expanding that just by adding a single value we couldn't do that the other way because when we take a value we're only allowed to move values to the left so just like we know that this subarray can't get any smaller the three can't get any smaller as a result our result will never be smaller than three we can use that same idea as we slowly expand this array like at this point when we just have two values here and what we're going to do of course is turn this guy into a five and turn this guy into a five once we get to this point we know that the result can't possibly be smaller than five so that's the idea behind this problem it's definitely not easy to come up with if I was your interviewer I would definitely give you a hint so now let's run through the algorithm we start at three and then we go to the next value seven what should we be doing here well our goal is to evenly distribute the values like if this is a 3 e and this is a 7 we want to evenly distribute the values how exactly can we do that well probably by taking the sum of the array and dividing it by the length of the sub array which is 2 in this case so in that case we would get 10 divided by 2 which is 5. we'd probably want to round up so in the case where we had something like 11 divided by 2 we'd get 5.5 but we'd probably want to round that up to 6 because remember we're trying to return the maximum so that's another observation to make then what do we do with that value five well we know that that's kind of the average of this subarray but in other words we know that this is going to be the maximum value so we would take this value and then assign it to the result but only if this value is actually greater than the result because notice the opposite case here what if these values were in the opposite order what if this was a 7 and this was a 3 then our initial result would have been seven by the time we're only at this part but then when we add this second value we have a sum of 10 we divide that by two now we get five should we take the five and assign it to our result no because if we previously saw a seven we're never gonna decrease the result so in other words we're always going to say result is equal to the maximum of itself and whatever this value is that we computed which in this case is five the reason is because as we mentioned earlier we can move values to the left but we can't move values to the right so now let's just kind of walk through the rest of this problem remember we calculated a five so that's what we're going to now reassign our result to and we don't really need to actually update the array so I'm not really going to do that but I guess I will just to kind of show you what it would look like but we don't really need to do that we just need to keep track of what our result is and also as we are adding new values like now we're going to visit this one one so this is our subarray at this point remember what we're doing is taking the sum of that sub array which now is going to be 11 and dividing it by the length which is 3 so this computation is pretty easy it's going to be less than 5 so we don't need to update our result in this case but another important observation is if we're keeping track of the total we probably don't want to have to recompute that every time so the easiest thing to do is just have like a variable to keep track of the total which I'm not really showing but it's pretty simple so I won't do that now lastly we get to this 6 here our total sum is now going to be 17 divide that by 4 which is the length and that's going to be 5 after we round up so our result is still not going to change and 5 is going to be the result that we ultimately return clearly the time complexity of this is not bad we're not using any advanced data structures we're just iterating through the array keeping track of the total and updating the result periodically so the time complexity is Big O of n memory complexity is Big O of 1. now let's code this up so the first thing I'm going to do is initialize our result to the first value in the array at index 0 and I'm also going to well before I do that actually since we're going to be iterating through every value in the input array except of course the first value so I'm going to say for in range starting at index 1 and then going up until the length of the array the reason we're skipping the first value is because we can't take values from the first value and move them to the left so it doesn't really make sense to do anything with the first one so what I'm also going to do is set our total AKA our prefix sum also to the first value so we're basically skipping the value at index 0 and then starting at index one now after we do that it's pretty straightforward just as I kind of talked about we're going to keep track of our total by just adding the value at index I every single time and also updating our result which is going to be the maximum of what it currently is as well as the total and we're going to divide by the length which is going to be I plus 1 because arrays are 0 indexed make sure not to forget that this operation we want to take the ceiling of it so math dot ceiling we want to round up that's what we're trying to do here so among these two values we want the maximum and we'll get that and we'll assign it to the result our result can never get any smaller and then we're just going to go ahead and return this I'll run it to make sure that it works and as you can see yes it does and it's pretty efficient though this was a small amount of code there's a lot of logic to it and I think it would be a decent interview question if your interviewer is willing to help you out I think it would make a good discussion trying to solve this problem if this was helpful please like And subscribe if you're preparing for coding interviews check out neat code.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon

Original Description

🚀 https://neetcode.io/ - A better way to prepare for Coding Interviews Solving Leetcode 2439 - Minimize Maximum of Array, today's daily leetcode problem on April 4th. 🥷 Discord: https://discord.gg/ddjKRXPqtk 🐦 Twitter: https://twitter.com/neetcode1 🐮 Support the channel: https://www.patreon.com/NEETcode ⭐ BLIND-75 PLAYLIST: https://www.youtube.com/watch?v=KLlXCFG5TnA&list=PLot-Xpze53ldVwtstag2TL4HQhAnC8ATf 💡 DYNAMIC PROGRAMMING PLAYLIST: https://www.youtube.com/watch?v=73r3KWiEvyk&list=PLot-Xpze53lcvx_tjrr_m2lgD2NsRHlNO&index=1 Problem Link: https://leetcode.com/problems/minimize-maximum-of-array/ 0:00 - Read the problem 0:30 - Drawing Explanation 7:55 - Coding Explanation leetcode 2439 #neetcode #leetcode #python
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeetCodeIO · NeetCodeIO · 0 of 60

← Previous Next →
1 Leetcode 149 - Maximum Points on a Line - Python
Leetcode 149 - Maximum Points on a Line - Python
NeetCodeIO
2 Design Linked List - Leetcode 707 - Python
Design Linked List - Leetcode 707 - Python
NeetCodeIO
3 Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
Minimum Time to Collect All Apples in a Tree - Leetcode 1443 - Python
NeetCodeIO
4 Design Browser History - Leetcode 1472 - Python
Design Browser History - Leetcode 1472 - Python
NeetCodeIO
5 Number of Good Paths - Leetcode 2421 - Python
Number of Good Paths - Leetcode 2421 - Python
NeetCodeIO
6 Flip String to Monotone Increasing - Leetcode 926 - Python
Flip String to Monotone Increasing - Leetcode 926 - Python
NeetCodeIO
7 Maximum Sum Circular Subarray - Leetcode 918 - Python
Maximum Sum Circular Subarray - Leetcode 918 - Python
NeetCodeIO
8 Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
Find Closest Node to Given Two Nodes - Leetcode 2359 - Python
NeetCodeIO
9 Concatenated Words - Leetcode 472 - Python
Concatenated Words - Leetcode 472 - Python
NeetCodeIO
10 Data Stream as Disjoint Intervals - Leetcode 352 - Python
Data Stream as Disjoint Intervals - Leetcode 352 - Python
NeetCodeIO
11 LFU Cache - Leetcode 460 - Python
LFU Cache - Leetcode 460 - Python
NeetCodeIO
12 N-th Tribonacci Number - Leetcode 1137
N-th Tribonacci Number - Leetcode 1137
NeetCodeIO
13 Best Team with no Conflicts - Leetcode 1626 - Python
Best Team with no Conflicts - Leetcode 1626 - Python
NeetCodeIO
14 Greatest Common Divisor of Strings - Leetcode 1071 - Python
Greatest Common Divisor of Strings - Leetcode 1071 - Python
NeetCodeIO
15 Shortest Path in a Binary Matrix - Leetcode 1091 - Python
Shortest Path in a Binary Matrix - Leetcode 1091 - Python
NeetCodeIO
16 Insert into a Binary Search Tree - Leetcode 701 - Python
Insert into a Binary Search Tree - Leetcode 701 - Python
NeetCodeIO
17 Delete Node in a BST - Leetcode 450 - Python
Delete Node in a BST - Leetcode 450 - Python
NeetCodeIO
18 Shuffle the Array (Constant Space) - Leetcode 1470 - Python
Shuffle the Array (Constant Space) - Leetcode 1470 - Python
NeetCodeIO
19 Fruits into Basket - Leetcode 904 - Python
Fruits into Basket - Leetcode 904 - Python
NeetCodeIO
20 Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
Number of Subarrays of size K and Average Greater than or Equal to Threshold - Leetcode 1343 Python
NeetCodeIO
21 Naming a Company - Leetcode 2306 - Python
Naming a Company - Leetcode 2306 - Python
NeetCodeIO
22 As Far from Land as Possible - Leetcode 1162 - Python
As Far from Land as Possible - Leetcode 1162 - Python
NeetCodeIO
23 Shortest Path with Alternating Colors - Leetcode 1129 - Python
Shortest Path with Alternating Colors - Leetcode 1129 - Python
NeetCodeIO
24 Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
Minimum Fuel Cost to Report to the Capital - Leetcode 2477 - Python
NeetCodeIO
25 Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
Count Odd Numbers in an Interval Range - Leetcode 1523 - Python
NeetCodeIO
26 Contains Duplicate II - Leetcode 219 - Python
Contains Duplicate II - Leetcode 219 - Python
NeetCodeIO
27 Path with Maximum Probability - Leetcode 1514 - Python
Path with Maximum Probability - Leetcode 1514 - Python
NeetCodeIO
28 Add to Array-Form of Integer - Leetcode 989 - Python
Add to Array-Form of Integer - Leetcode 989 - Python
NeetCodeIO
29 Unique Paths II - Leetcode 63 - Python
Unique Paths II - Leetcode 63 - Python
NeetCodeIO
30 Minimum Distance between BST Nodes - Leetcode 783 - Python
Minimum Distance between BST Nodes - Leetcode 783 - Python
NeetCodeIO
31 Design Hashmap - Leetcode 706 - Python
Design Hashmap - Leetcode 706 - Python
NeetCodeIO
32 Range Sum Query Immutable - Leetcode 303 - Python
Range Sum Query Immutable - Leetcode 303 - Python
NeetCodeIO
33 Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
Binary Tree Zigzag Level Order Traversal - Leetcode 103 - Python
NeetCodeIO
34 Middle of the Linked List - Leetcode 876 - Python
Middle of the Linked List - Leetcode 876 - Python
NeetCodeIO
35 Course Schedule IV - Leetcode 1462 - Python
Course Schedule IV - Leetcode 1462 - Python
NeetCodeIO
36 Single Element in a Sorted Array - Leetcode 540 - Python
Single Element in a Sorted Array - Leetcode 540 - Python
NeetCodeIO
37 Capacity to Ship Packages - Leetcode 1011 - Python
Capacity to Ship Packages - Leetcode 1011 - Python
NeetCodeIO
38 IPO - Leetcode 502 - Python
IPO - Leetcode 502 - Python
NeetCodeIO
39 Minimize Deviation in Array - Leetcode 1675 - Python
Minimize Deviation in Array - Leetcode 1675 - Python
NeetCodeIO
40 Longest Turbulent Array - Leetcode 978 - Python
Longest Turbulent Array - Leetcode 978 - Python
NeetCodeIO
41 Last Stone Weight II - Leetcode 1049 - Python
Last Stone Weight II - Leetcode 1049 - Python
NeetCodeIO
42 Construct Quad Tree - Leetcode 427 - Python
Construct Quad Tree - Leetcode 427 - Python
NeetCodeIO
43 Find Duplicate Subtrees - Leetcode 652 - Python
Find Duplicate Subtrees - Leetcode 652 - Python
NeetCodeIO
44 Sort an Array - Leetcode 912 - Python
Sort an Array - Leetcode 912 - Python
NeetCodeIO
45 Ones and Zeroes - Leetcode 474 - Python
Ones and Zeroes - Leetcode 474 - Python
NeetCodeIO
46 Remove Duplicates from Sorted Array II - Leetcode 80 - Python
Remove Duplicates from Sorted Array II - Leetcode 80 - Python
NeetCodeIO
47 Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
Maximum Twin Sum of a Linked List - Leetcode 2130 - Python
NeetCodeIO
48 Concatenation of Array - Leetcode 1929 - Python
Concatenation of Array - Leetcode 1929 - Python
NeetCodeIO
49 Symmetric Tree - Leetcode 101 - Python
Symmetric Tree - Leetcode 101 - Python
NeetCodeIO
50 Check Completeness of a Binary Tree - Leetcode 958 - Python
Check Completeness of a Binary Tree - Leetcode 958 - Python
NeetCodeIO
51 Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
Construct Binary Tree from Inorder and Postorder Traversal - Leetcode 106 - Python
NeetCodeIO
52 Find Peak Element - Leetcode 162 - Python
Find Peak Element - Leetcode 162 - Python
NeetCodeIO
53 Accounts Merge - Leetcode 721 - Python
Accounts Merge - Leetcode 721 - Python
NeetCodeIO
54 Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
Binary Tree Preorder Traversal (Iterative) - Leetcode 144 - Python
NeetCodeIO
55 Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
Binary Tree Postorder Traversal (Iterative) - Leetcode 145 - Python
NeetCodeIO
56 Number of Zero-Filled Subarrays - Leetcode 2348 - Python
Number of Zero-Filled Subarrays - Leetcode 2348 - Python
NeetCodeIO
57 Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
Minimum Score of a Path Between Two Cities - Leetcode 2492 - Python
NeetCodeIO
58 Sqrt(x) - Leetcode 69 - Python
Sqrt(x) - Leetcode 69 - Python
NeetCodeIO
59 Successful Pairs of Spells and Potions - Leetcode 2300 - Python
Successful Pairs of Spells and Potions - Leetcode 2300 - Python
NeetCodeIO
60 Optimal Partition of String - Leetcode 2405 - Python
Optimal Partition of String - Leetcode 2405 - Python
NeetCodeIO

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python

Chapters (3)

Read the problem
0:30 Drawing Explanation
7:55 Coding Explanation
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →