Posts

Showing posts from March, 2023

Binary Search to Find Next Greater Element II

Image
Very similar problem as solved in a different blog post, the only caveat here is that if the result of the Binary Search does not yield a greater value than the target, return the smallest one ( this is the difference that I'm referring to). Code is down below, cheers, ACC. Maximize Greatness of an Array - LeetCode 2592. Maximize Greatness of an Array Medium 220 4 Add to List Share You are given a 0-indexed integer array  nums . You are allowed to permute  nums  into a new array  perm  of your choosing. We define the  greatness  of  nums  be the number of indices  0 <= i < nums.length  for which  perm[i] > nums[i] . Return  the  maximum  possible greatness you can achieve after permuting   nums .   Example 1: Input: nums = [1,3,5,2,1,3,1] Output: 4 Explanation: One of the optimal rearrangements is perm = [2,5,1,3,3,1,1]. At indices = 0, 1, 3, and 4, perm[i] > nums[i]. Hence, we retu...

Standard Priority Queue III

Image
Another problem involving Priority Queues. Key point here is to create the weight that includes the value and the index. Standard way of doing that would be value*[MaxIndex + constant] + index. Use a hash table to mark the used cells and neighbors. Code is down below, cheers, ACC. Find Score of an Array After Marking All Elements - LeetCode 2593. Find Score of an Array After Marking All Elements Medium 184 2 Add to List Share You are given an array  nums  consisting of positive integers. Starting with  score = 0 , apply the following algorithm: Choose the smallest integer of the array that is not marked. If there is a tie, choose the one with the smallest index. Add the value of the chosen integer to  score . Mark  the chosen element and its two adjacent elements if they exist . Repeat until all the array elements are marked. Return  the score you get after applying the above algorithm .   Example 1: Input: nums = [2,1,3,4,5,2] Output: 7 Explana...

Trees, Priority Queue, Hash Tables and DFS all at once

Image
Problem here is a Tree problem but the solution requires multiple steps. First, using a DFS create the sum of levels and store in a Hash Table. Then, push the content to a Priority Queue. Finally, dequeue in order to find your answer. Code is down below, cheers, ACC. 2583. Kth Largest Sum in a Binary Tree Medium 97 3 Add to List Share You are given the  root  of a binary tree and a positive integer  k . The  level sum  in the tree is the sum of the values of the nodes that are on the  same  level. Return  the  k th   largest  level sum in the tree (not necessarily distinct) . If there are fewer than  k  levels in the tree, return  -1 . Note  that two nodes are on the same level if they have the same distance from the root.   Example 1: Input: root = [5,8,9,2,1,3,7,4,6], k = 2 Output: 13 Explanation: The level sums are the following: - Level 1: 5. - Level 2: 8 + 9 = 17. - Level 3: 2 + 1 + 3 + 7 = 13. ...