Posts

Showing posts from March, 2026

This is a Graph Problem - Not a Tree Problem! Part IV

Image
I think this problem had everything: hashtables, hashsets, recursive DFS and non-recursive DFS and even applications of the dangerous .GetHashCode(), which I don't like but sometimes it is good enough when the constraints are limited, which is the case of this problem. But the problem isn't a tree problem - it is a graph one. Convert the tree to a graph (needed because you'll be navigating up and down the tree), and that's where I'm using .GetHashCode() to uniquely identify the nodes (worked), then for each node (non-recursive DFS) perform a search (recursive DFS) looking for the max path, traversing only in the case of unique numbers. Notice that you need to keep going even if you find a -ve node since there might be a larger unvisited number behind that node. Code is down below, cheers, ACC. Maximum Distinct Path Sum in a Binary Tree - LeetCode You are given the  root  of a  binary tree , where each node contains an integer value. A  valid path  in the tree is...

Greedy Approach I

Image
On a first glance, a greedy approach for this problem might seem intractable, but it isn't. The fact that the numbers are all unique really help here. Bucket them up into two sorted sets, one for even and one for odd numbers. Then greedily try even first, then odd. When trying even, you can quickly calculate for each number whether there is a possibility to use the second rule. The same for the odd case. When doing that, despite being a greedy approach (trying all possibilities), it runs very quickly in nlogn (a linear approach should be feasible too). Code is down below, cheers, ACC. Construct Uniform Parity Array II - LeetCode ou are given an array  nums1  of  n   distinct  integers. You want to construct another array  nums2  of length  n  such that the elements in  nums2  are either  all odd or all even . For each index  i , you must choose  exactly one  of the following (in any order): nums2[i] = nums1[i] ​​...