From N^2 to N

Problem is here: https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/

1026. Maximum Difference Between Node and Ancestor
Medium
Given the root of a binary tree, find the maximum value V for which there exists different nodes A and B where V = |A.val - B.val| and A is an ancestor of B.
(A node A is an ancestor of B if either: any child of A is equal to B, or any child of A is an ancestor of B.)

Example 1:
Input: [8,3,10,1,6,null,14,null,null,4,7,13]
Output: 7
Explanation: 
We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.

Note:
  1. The number of nodes in the tree is between 2 and 5000.
  2. Each node will have value between 0 and 100000.
An N^2 approach seems at a glance to be the most logical approach: for each node, do a DFS traversal, calculate the value |node.val - eachChild|, and keep track of the max. Given than N = 5000, this might work (total 25,000,000 iterations..). However, there is a way to do it in N:

If you think about the problem carefully, you'll realize that inevitably your answer will be of the form |A-B| where either A is the largest value in your tree, or B is the smallest. To prove this lemma, suppose that your solution is |A-B| and suppose that you have found another node C such that C<B. Well, |A-C| will be clearly be larger than |A-B|, hence |A-B| cannot be your solution.

That being said, you can do a post-order DFS keeping track of the min/max, bubbling that up in the recursion. At each step, check if you have a maxDiff using the current node, min and max. And you accomplish O(N)-time. Cheers, ACC.


public class Solution
{
public int MaxAncestorDiff(TreeNode root)
{
int maxDiff = -1;
int min = -1;
int max = 100001;

MaxAncestorDiff(root, ref maxDiff, ref min, ref max);

return maxDiff;
}

private void MaxAncestorDiff(TreeNode node,
ref int maxDiff,
ref int min,
ref int max)
{
if (node == null) return;

int minLeft = 100001;
int maxLeft = -1;
MaxAncestorDiff(node.left, ref maxDiff, ref minLeft, ref maxLeft);

int minRight = 100001;
int maxRight = -1;
MaxAncestorDiff(node.right, ref maxDiff, ref minRight, ref maxRight);

min = Math.Min(minLeft, minRight);
max = Math.Max(maxLeft, maxRight);

maxDiff = Math.Max(maxDiff, Math.Max(node.val - min, max - node.val));

min = Math.Min(min, node.val);
max = Math.Max(max, node.val);
}
}

Comments

Post a Comment

[フレーム]

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC. Process String with Special Operations I - LeetCode You are given a string  s  consisting of lowercase English letters and the special characters:  * ,  # , and  % . Build a new string  result  by processing  s  according to the following rules from left to right: If the letter is a  lowercase  English letter append it to  result . A  '*'   removes  the last character from  result , if it exists. A  '#'   duplicates  the current  result  and  appends  it to itself. A  '%'   reverses  the current  result . Return the final string  result  after processing all char...

Shortest Bridge – A BFS Story (with a Twist)

Here's another one from the Google 30 Days challenge on LeetCode — 934. Shortest Bridge . The goal? Given a 2D binary grid where two islands (groups of 1s) are separated by water (0s), flip the fewest number of 0s to 1s to connect them. Easy to describe. Sneaky to implement well. 🧭 My Approach My solution follows a two-phase Breadth-First Search (BFS) strategy: Find and mark one island : I start by scanning the grid until I find the first 1 , then use BFS to mark all connected land cells as 2 . I store their positions for later use. Bridge-building BFS : For each cell in the marked island, I run a BFS looking for the second island. Each BFS stops as soon as it hits a cell with value 1 . The minimum distance across all these searches gives the shortest bridge. πŸ” Code Snippet Here's the core logic simplified: public int ShortestBridge(int[][] grid) { // 1. Mark one island as '2' and gather its coordinates List<int> island = FindAndMark...

Classic Dynamic Programming IX

A bit of vibe code together with OpenAI O3. I asked O3 to just generate the sieve due to laziness. Sieve is used to calculate the first M primes (when I was using Miller-Rabin, was giving me TLE). The DP follows from that in a straightforward way: calculate the numbers from i..n-1, then n follows by calculating the min over all M primes. Notice that I made use of Goldbach's Conjecture as a way to optimize the code too. Goldbach's Conjecture estates that any even number greater than 2 is the sum of 2 primes. The conjecture is applied in the highlighted line. Cheers, ACC. PS: the prompt for the sieve was the following, again using Open AI O3 Advanced Reasoning: " give me a sieve to find the first M prime numbers in C#. The code should produce a List<int> with the first M primes " Minimum Number of Primes to Sum to Target - LeetCode You are given two integers  n  and  m . You have to select a multiset of  prime numbers  from the  first   m  pri...