Find the Maximum Sum of Node Values - Leetcode 3068 - Python

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

Key Takeaways

The video demonstrates how to solve Leetcode problem 3068, finding the maximum sum of node values in an undirected graph that is a tree, using Python and a greedy algorithm with XOR operations.

Full Transcript

hey everyone welcome back and let's write some more neat code today so today let's solve the problem find the maximum sum of node values so this is a hard problem and 100% I'm going to show you how to solve this problem efficiently but if there's anything you take away from this video hopefully it is how to kind of approach really difficult problems and learn some problem solving skills from it those problem solving skills might not necessarily lead you to the correct solution every single time but still these are useful skills and that's really what I try to so we're given an undirected graph that is specifically a tree so immediately we should be familiar with what a tree is if we're trying to solve this problem if you don't know what a tree is I wouldn't even bother with this problem and I'm not trying to be mean I'm just trying to be honest tree is a connected graph that does not have Cycles in it so no Cycles to worry about the fact that it's connected is really the most important thing and that's going to be very relevant to the rest of this problem because as you may know with a connected graph and specifically this one is undirected there is going to exist a path from any two given nodes in the graph any two given nodes there's going to be a path connecting them so keep that in mind we are also given an integer K so K could be anything this is really the most important parameter because what we are trying to do take this graph for example since it's the simplest one we have a node zero and one now these are like the labels because we're given these nodes in a array so this will be at the zeroth index this will be at the first index but these are not the values of this graph so if you look down here the value of this one is actually going to be two and the value of this one is actually going to be three so I think that's what I'm going to put here the value K in this example is seven the idea in this problem is that we can take any Edge this one is simple there's just a single edge but we can take any Edge and when we pick this Edge what we do is say take this value over here and xor it with seven and at the same time we have to take the other value attached to that edge and exort it with seven as well and the result is going to be the new value for each of these respective nodes and they kind of mention down here in the description that 2 exord with seven is going to be five and three exord with seven is going to be four so these are going to be the new values so then we'd put a five over here and we'd put a four over here ultimately what we're trying to do here is maximize the total sum of all the values of the nodes so right now it looks like we increased them previously the sum was 2 + 3 that's 5 now the sum is 5 + 4 that's nine so we've increased it but this is such a simple example let's go again let's see if we can notice anything let's try to make it even bigger now I'm going to take five and now I'm going to exort it down here cuz we have some empty space I'm going to exort five with that same number K they don't really tell us in this problem we can't do that same operation on an edge multiple times so screw it that's what I'm going to do 5 xord with seven and four exord with seven the result of this one is going to be two and the result of this one funny enough is going to be three does that look familiar to you it does to me it looks like we just got the original values back again um is that a coincidence because when I'm looking at a problem like this one the first thing I'm trying to do isn't actually solve the problem because this is a hard problem I wouldn't be able to solve it in a few minutes I don't immediately read this and automatically know how to solve it I start to look for Clues and one of the clues I was looking for is this operation that we're doing here is the xor operation right they tell us what that operation is like well they don't tell us what it is but we know what it is but basically it's not like some random operation that we're doing what I'm getting at is this operation is not a black box we can possibly get some clues about how to solve this problem or optimize this problem by thinking about what this operation is actually doing take a look at this let's look at this when you have two exord with 7 in binary two looks like this uh 0 1 0 seven in binary is this this is one this is two and this is four so if you add those up then you get seven so if we exor this we're looking for the spots that that there's only a single one so we put a one over here there's a double one over here so we put zero there's a single one over here so we put one in other words when you look at the original number either what's going to happen a zero could possibly turn into a one if that happens like from the original number a zero turns into a one like uh down here that must mean that there was a one over here and then on the next time if we take this same exact number number and try to exort it with the result of this then we're going to turn that one back into a zero cuz now we have double ones over here if you have a one and you turn it into a zero then the next time you exort it with the same number it's going to be turned into a zero and of course we could look at the case where you have double zeros and double ones that's kind of what we're doing here actually but ultimately the biggest thing to notice about the xor operation is if you have some integer n and then you exor it with a given integer K and then you exort it with that given integer K again the result is always going to be n this is a key observation if there ever existed a key observation in any problem but even this is not enough let me tell you one more hint and I bet you'll be able to solve the problem without even watching the rest of this video remember what I mentioned earlier that any two nodes are connected well let's take a look at this example and really drive that point home we only have two edges here so it's a little bit more complicated than this example but still it's pretty simple suppose I take this Edge and I do that exor operation okay so we end up xoring this one a single time we end up xoring this one and then suppose I choose this Edge so we end up xoring this one twice and then exing this one Once In other words we exor this one twice so we don't actually change it we only end up changing these two now suppose to make it even more interesting I introduce a new node over here and now I say I'm going to exort this one twice because I choose this Edge and then I exort this and I also exort this in other words we don't exort this one at all so let me just redraw this this would be the result this one gets exord and this one gets exord and then these two in the middle actually stay the same and if there was like some path here we could continue doing that so what we're noticing here is very very important we already know that if we choose the exort operation we have to pick an edge therefore we have to exort two nodes but those two nodes actually don't need to be adjacent it's true that we can't just pick one node and exort it that's 100% true we can't just pick one we have to to exort two nodes at a time but those two nodes don't have to be connected by an edge they can actually be anywhere in the graph any two nodes at a time that's what I'm saying that this problem the way it was worded was actually wrong we have discovered a simpler version of the exact same problem we've rewarded the problem we changed it now we're allowed to pick any two nodes in the graph and xor them at a time given this information can you now solve this problem in a relatively efficient way well I'm going to show you exactly how to so what we're realizing is that for any given node we really have two choices either we leave it the same or we exort that node but also keep in mind that if we exort any given node we must exort at least another node any other node in the graph this is like our choice right we either exort two nodes or we don't do anything of course for any any given node it only has two possible values the original value or the exord value so it's not like there are an infinite possibility of values that any node could be so this is kind of simplifying the problem given this I think there actually are multiple ways to solve this problem I'm going to show you the one that I was able to come up with by myself I think it's a relatively simple one um maybe there's a more simple one you can feel free to talk about that in the comments I guess if you found a better one remember that ultimately we are trying to maximize the total sum of values so we'd only want to do an xor operation if we increase the total sum of values so what we should do is first of all just look at the Delta which values are going to end up being increased by the xor operation and which ones are going to be decreased let's go through every single value and figure out the Delta after xoring it and to make this interesting let's look at the biggest example actually it looks like all the values in that are the exact same so that's not going to be too interesting let's uh focus on this one so I'm just going to add like the actual value of every single one of these next to it so I think this one is a one this one is a two and this one is a one based on this down here and K is equal to three in binary this is one in binary this is two in binary this is three if we were to X or one with three so we' take these two and exord them it would look like we'd get two as a result so I'm going to put the exord version second so this is going to be a two and so obviously this one would end up being the same and two exord with three down here is just going to be one So that obviously makes sense cuz two is going to be turned back into one so we'd expect a two to be turned into a one okay so just to draw it a little bit bigger this was our original array of nums now now we create another array that I'm going to call Delta and that is for each of these was this one increased or decreased when we exort it well it turned into a two which you can see like over there so obviously the Delta was A+ one two turned into a 1 so the Delta was a negative 1 and then this turned into a two so the Delta was a plus one okay now this is what we care about like this is our original sum so let's just say that so far the total happens to be four originally can we increase that total at all well we can pick this + one Delta we can pick this plus one Delta and then add two to the total well imagine for a second that this input array was actually all ones three ones and then this was also like a plus one over here would we be able to pick all three plus ones you tell me based on what I told you earlier would we be able to pick all three of these no there's a reason for that try to think about it this is an odd number remember we can only pick two at a time so in the context of this problem when I say I'm picking both of these this one and this one I'm saying that I'm choosing this path I'm picking this node to exor and I'm picking this node to exor and I'm choosing this path and obviously if this graph was a little bit different like if this part was like the one and this one was like the two I know this is really messy I'm sorry about that but basically what I'm saying is then we would have chosen this node to exor and this node to exor therefore we would be choosing this path over here that kind of looks like an A or whatever like this notice that these two nodes are not adjacent to each other but they are connected by a path therefore this one does not get exor that's what I'm saying okay now knowing all of that if you believe me how do we solve this problem programmatically we can't just look at the Delta array and just pick them well this is the part where we get really really greedy and we take the Delta array and we sort it in descending order because we want to pick the biggest guys and we want to put all the big values at the beginning so that's what we're going to do we're going to take Delta array we're going to sort it it's going to look like this 1 one and negative 1 we're going to go two at a time like we're going to look at two adjacent values each time we're going to look at both of them we're going to add both of them up and we're going to say is the sum of these two positive is it greater than zero if it is go ahead and add it to the total and keep going now look at the next two values well this time there aren't two values left right so this is the part where we say okay we can't do anything like there just aren't enough values to look at so even if this one was a plus one we wouldn't be able to add all three of them now to make it I guess a tiny bit more interesting let's go ahead and actually add a negative one over here I guess in the context of this problem that would pretty much mean creating a node over here that has a value of two so this is the value and then it turns into a one after we exor it so we do have two values left this time but should we add them to the total probably not cuz why why would we They Don't Really contribute anything they actually make our total even smaller so we don't include these we do include these we get a total of 2 + 4 that's going to be six it looks to me that is the correct result of this problem so this is the explanation of the problem the overall time complexity is going to basically be bottlenecked by the Sorting that is going to be n log in but I do think there actually are other solutions to this problem that actually are just Big O of n but I feel like this is such a hard problem that I want this video to appeal to a wide variety of people that I think showing you this slightly more simple and slightly less efficient solution is actually fine cuz this one does pass as well I would hope that in a real interview this would most likely be enough I really really believe that even at Google this would more than be enough also I want to say that this is harder than the average problem you will see at a company like Google 100% And if someone does ask you this question they will almost certainly give you some hints just like I did in the video also of course we do use extra space so space complexity is going to be big oent let's code it up so I guess before I actually clear this I might as well show you like this is how I was able to like approach this problem again like this is a very difficult one don't feel bad if you weren't able to solve it by yourself this was like my main thought process it may or may not help you but let's actually get into the solution now we know that the main way to solve this problem is going to rely on this Delta array in Python it's pretty easy to actually get it we're going to use something called list comprehension so for every number in in the input we want to map it to this we want to take n and exort it with K of course but that's not the Delta right that's just the new version of that number to get the Delta we take the new version and subtract the old version so either it increased or it decreased maybe it stayed the same but overall we care about the Delta and remember we want to sort this as well we're going to sort it in descending order you could I guess sort it in ascending order if you wanted to and then just iterate over in reverse order but why would we do that and we want to obviously compute the result which is going to be the maximum sum of all the values and then return that and initially we actually don't need to set it to zero we actually can set it equal to the sum of the input and then now we can try to maximize it so remember we're going to look at values two at a time in the Delta array so I'm going to say for I in range in Python you kind of have to do it like this so from zero all the way to the last index I guess length of nums this will pretty much be the last index though since this is non-inclusive in Python and also we want to increment our ey pointer by two every single time so that's what this is saying now what I'm trying to do here I guess is take the value at index I in Delta and take the value at index I + 1 in Delta now immediately you can see we might not have an i + one what if we were given an odd number of values we're not going to have an i+1 at some point so before we even do that computation we don't want an index out of bounds let's just say if I is the last Index right now then we don't have a plus one and at that point we should just break out of this Loop okay so if that's not the case then we compute this sum we call it our path Delta or you could say the total Delta it doesn't really matter at this point this isn't really a graph problem at all so we don't really need to call it the path but oh well of course we want to take this path Del and add it to the result but we only want to do that if it's positive in other words if at any point we get a path Delta that is less than or equal to zero at that point we're never going to increase our result anyway remember this array is sorted if these two aren't greater than zero then there's not going to be any values greater than zero in the rest of the array so at that point we might as well just break out of it this is the entire code it doesn't look too difficult does it but remember this first line over here is the hard part it relies on quite a bit of intuition to come up with so I'm going to go ahead and run it as you can see on the left it works and it is shockingly efficient even though there are linear time solutions for this problem that just kind of goes to show you that leak code is pretty random if you found this helpful check out N.O for a lot more thanks for watching and I'll see you soon

Original Description

🚀 https://neetcode.io/ - A better way to prepare for Coding Interviews 🧑‍💼 LinkedIn: https://www.linkedin.com/in/navdeep-singh-3aaa14161/ 🐦 Twitter: https://twitter.com/neetcode1 ⭐ BLIND-75 PLAYLIST: https://www.youtube.com/watch?v=KLlXCFG5TnA&list=PLot-Xpze53ldVwtstag2TL4HQhAnC8ATf Problem Link: https://leetcode.com/problems/find-the-maximum-sum-of-node-values/ 0:00 - Read the problem 0:30 - Drawing Explanation 14:32 - Coding Explanation leetcode 3068 #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

This video teaches how to solve Leetcode problem 3068 by finding the maximum sum of node values in an undirected graph that is a tree, using a greedy algorithm with XOR operations in Python. The goal is to maximize the total sum of all node values by selecting nodes with positive Delta values. The video provides a step-by-step guide on how to analyze the XOR operation, choose nodes for the XOR operation, and implement the greedy algorithm.

Key Takeaways
  1. Analyze the XOR operation to gain clues about solving the problem
  2. Choose any two nodes in the graph for the XOR operation
  3. Look at the Delta values for each node after performing an XOR operation
  4. Select nodes with positive Delta values to maximize the total sum of values
  5. Sort the Delta array in descending order
  6. Pick two adjacent values at a time and add them up
  7. Check if the sum is positive and add it to the total if it is
  8. Continue until there are not enough values to look at
  9. Return the total
💡 The XOR operation can be used to increase the total sum of values by selecting nodes with positive Delta values

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
14:32 Coding Explanation
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →