Posts

Showing posts from April, 2023

Standard Priority Queue IV

Image
Easy Sunday Morning LC problem: straight pQueue implementation. Code is down below, cheers, ACC. Maximum Sum With Exactly K Elements - LeetCode 2656. Maximum Sum With Exactly K Elements Easy 54 2 Add to List Share You are given a  0-indexed  integer array  nums  and an integer  k . Your task is to perform the following operation  exactly   k  times in order to maximize your score: Select an element  m  from  nums . Remove the selected element  m  from the array. Add a new element with a value of  m + 1  to the array. Increase your score by  m . Return  the maximum score you can achieve after performing the operation exactly   k   times.   Example 1: Input: nums = [1,2,3,4,5], k = 3 Output: 18 Explanation: We need to choose exactly 3 elements from nums to maximize the sum. For the first iteration, we choose 5. Then sum is 5 and nums = [1,2,3,4,6] For the second iteration, we choose...

Old fashioned boolean

Image
People don't give much credit anymore to George Boole ( George Boole - Wikipedia ), but that's a mistake, a simple boolean operation can save you a lot of time and space. This problem exemplifies it. Given the low boundaries (N=50), an N^2 solution works fine and the use of a simple boolean array makes it an elegant solution too. Code is down below, cheers, ACC. Find the Prefix Common Array of Two Arrays - LeetCode 2657. Find the Prefix Common Array of Two Arrays Medium 30 1 Add to List Share You are given two  0-indexed  integer   permutations  A  and  B  of length  n . A  prefix common array  of  A  and  B  is an array  C  such that  C[i]  is equal to the count of numbers that are present at or before the index  i  in both  A  and  B . Return  the  prefix common array  of  A  and  B . A sequence of  n  integers is called a...

Cousins in a Binary Tree

Image
Interesting problem about cousins  in a binary tree. Cousins as the name implies are all the nodes in the same level that have different parent nodes. Idea here is two-fold: 1/ First, perform a DFS and calculate the sum of all values per level. Use a Hashtable. This is done in linear time. 2/ Then, perform another DFS (also linear time) this time setting the values of the children. Do some calculation to get the sum of the siblings, and using the Hashtable calculated in #1, set the proper value for each child node Code is down below, cheers, ACC. Cousins in Binary Tree II - LeetCode 2641. Cousins in Binary Tree II Medium 37 1 Add to List Share Given the  root  of a binary tree, replace the value of each node in the tree with the  sum of all its cousins' values . Two nodes of a binary tree are  cousins  if they have the same depth with different parents. Return  the  root  of the modified tree . Note  that the depth of a node is the ...