question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
minimum-number-of-moves-to-make-palindrome | TypeScript Greedy faster that 100% | typescript-greedy-faster-that-100-by-kam-s2yt | \nfunction minMovesToMakePalindrome(s: string): number {\n let leftIndex = 0\n let rightIndex = s.length - 1\n const sArr: string[] = Array.from(s)\n | kamrankoupayi | NORMAL | 2022-04-02T14:38:52.972330+00:00 | 2022-04-02T14:38:52.972369+00:00 | 187 | false | ```\nfunction minMovesToMakePalindrome(s: string): number {\n let leftIndex = 0\n let rightIndex = s.length - 1\n const sArr: string[] = Array.from(s)\n let sumChange = 0\n \n while(leftIndex < rightIndex){\n if(sArr[leftIndex] === sArr[rightIndex]){\n leftIndex ++\n rightIndex --\n continue\n }\n let matchRight = leftIndex + 1\n let matchLeft = rightIndex - 1\n \n while(sArr[matchRight] !== sArr[rightIndex]){\n matchRight++\n }\n while(sArr[matchLeft] !== sArr[leftIndex]){\n matchLeft--\n }\n if(matchRight - leftIndex <= rightIndex - matchLeft){\n sumChange += matchRight - leftIndex\n sArr.splice(matchRight, 1)\n sArr.splice(leftIndex, 0, s[rightIndex])\n }else{\n sumChange += rightIndex - matchLeft\n sArr.splice(rightIndex + 1, 0, s[leftIndex])\n sArr.splice(matchLeft, 1)\n }\n leftIndex ++\n rightIndex --\n }\n return sumChange\n};\n``` | 1 | 0 | [] | 0 |
minimum-number-of-moves-to-make-palindrome | C++ Greedy Solution O(N ^ 2) | c-greedy-solution-on-2-by-ahsan83-02eg | Runtime: 31 ms, faster than 47.44% of C++ online submissions for Minimum Number of Moves to Make Palindrome.\nMemory Usage: 6.8 MB, less than 50.32% of C++ onli | ahsan83 | NORMAL | 2022-03-15T04:53:30.891664+00:00 | 2022-03-15T04:54:45.318316+00:00 | 366 | false | Runtime: 31 ms, faster than 47.44% of C++ online submissions for Minimum Number of Moves to Make Palindrome.\nMemory Usage: 6.8 MB, less than 50.32% of C++ online submissions for Minimum Number of Moves to Make Palindrome.\n\n```\nTo make string palindrome we can keep left half of string in exact position and change \nthe right half chars using swaps from from two end point.\n```\n\n```\nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s) {\n\n int sl = s.length();\n\n // left and right end pointers\n int left = 0;\n int right = sl - 1;\n \n // count number of swaps\n int swapCount = 0;\n\n // loop through string from both side using left and right pointer\n while (left < right)\n {\n // if left and right pointer chars are not same then \n // find the rightmost position X of left pointer char\n // then swap from X to right pointer and increment swap count \n if (s[left] != s[right])\n {\n int l = left;\n int r = right;\n \n // get the right most index of s[l] char\n while(s[l]!=s[r])r--;\n \n // only swap once if s[l] is single char in range left and right\n if (l == r) {\n swap(s[r], s[r + 1]);\n swapCount++;\n continue;\n }\n \n // swap from r to right and increment count\n while(r<right)\n {\n swap(s[r+1],s[r]);\n r++;\n swapCount++;\n }\n }\n\n // reduce right and left pointer from both side in each step\n left++;\n right--;\n }\n\n return swapCount;\n }\n};\n``` | 1 | 0 | ['Two Pointers', 'Greedy', 'C'] | 0 |
minimum-number-of-moves-to-make-palindrome | [Java] greedy with explanation | java-greedy-with-explanation-by-jaylenzh-frpq | Each time we check the first and the last character. If they are the same, we can quickly shrink this problem into a subproblem with the size of n - 2. \nIf the | jaylenzhang19 | NORMAL | 2022-03-09T02:42:33.821624+00:00 | 2022-03-09T02:51:43.720210+00:00 | 396 | false | Each time we check the first and the last character. If they are the same, we can quickly shrink this problem into a subproblem with the size of n - 2. \nIf they are not the same, such as "a..b..a..b", then the answer becomes which character we need to choose as the end of both sides. If we choose \'a\', we need to move the last \'a\' to the end, and the cost will be the distance between the last \'b\' and the last \'a\'; If we choose \'b\', we need to move the first \'b\' to the beginning, the cost will be the distance between the first \'a\' and the first \'b\'. Therefore, we apply a greedy strategy picking the less costly one. \nWe apply this greedy strategy recursively until the size of the string less than or equal to 2(that would be the base case).\n```\npublic class Solution {\n public int minMovesToMakePalindrome(String s) {\n List<Character> list = new ArrayList<>();\n for (char c : s.toCharArray()) {\n list.add(c);\n }\n return helper(list);\n }\n\n private int helper(List<Character> list) {\n if (list.size() <= 2) return 0;\n int beginning = 0;\n int end = list.size() - 1;\n // both ends are the same\n if (list.get(beginning) == list.get(end)) {\n list.remove(end);\n list.remove(beginning);\n return helper(list);\n }\n // find the last \'a\'\n int lastA = end;\n while (lastA > beginning) {\n if (list.get(lastA) == list.get(beginning)) break;\n lastA -= 1;\n }\n // find the first \'b\'\n int firstB = beginning;\n while (firstB < end) {\n if (list.get(firstB) == list.get(end)) break;\n firstB += 1;\n }\n if (firstB - beginning <= end - lastA) {\n list.remove(end);\n list.remove(firstB);\n return firstB - beginning + helper(list);\n } else {\n list.remove(lastA);\n list.remove(0);\n return end - lastA + helper(list);\n }\n\n }\n} | 1 | 0 | [] | 0 |
minimum-number-of-moves-to-make-palindrome | C# Solution without swapping, uses maths | c-solution-without-swapping-uses-maths-b-pw8r | \npublic class Solution {\n public int MinMovesToMakePalindrome (string s) {\n int sum = 0;\n List<char> chars = s.ToCharArray ().ToList ();\n | 10f | NORMAL | 2022-03-08T23:36:07.047032+00:00 | 2022-03-08T23:36:07.047076+00:00 | 267 | false | ```\npublic class Solution {\n public int MinMovesToMakePalindrome (string s) {\n int sum = 0;\n List<char> chars = s.ToCharArray ().ToList ();\n int b = 0, e = chars.Count - 1;\n while (b < e) {\n if (chars[b] != chars[e]) {\n int maxIx = -1;\n for (int i = e - 1; i > b; i--) {\n if (chars[i] == chars[b]) {\n maxIx = i;\n break;\n }\n }\n // check if this is a single letter that needs to be in the middle, \n // the way the maths works for the middle letter is that we are leaving it\n // to swap it in the end - in order to reduce unneccessary swaps\n // and in the end when everything is in place, the cost to swap this letter\n // and put in in the middle will be the cost to put in in the middle right now\n if (maxIx == -1) {\n sum += (e - b) / 2;\n chars.RemoveAt (b);\n } \n // the cost to swap the rightmost letter that\'s the same with the current left\n // letter will be the endIndex - currentIndex\n else {\n sum += e - maxIx;\n chars.RemoveAt (maxIx);\n chars.RemoveAt (b);\n }\n } else {\n chars.RemoveAt (e);\n chars.RemoveAt (b);\n }\n e = chars.Count - 1;\n }\n return sum;\n }\n}\n``` | 1 | 0 | ['Math'] | 0 |
minimum-number-of-moves-to-make-palindrome | [Javascript] Two Pointer | javascript-two-pointer-by-vj98-qr24 | \n/**\n * @param {string} s\n * @return {number}\n */\nvar minMovesToMakePalindrome = function(s) {\n let left = 0, right = s.length-1, ans = 0;\n \n \ | vj98 | NORMAL | 2022-03-06T04:26:02.431726+00:00 | 2022-03-06T04:26:02.431773+00:00 | 723 | false | ```\n/**\n * @param {string} s\n * @return {number}\n */\nvar minMovesToMakePalindrome = function(s) {\n let left = 0, right = s.length-1, ans = 0;\n \n \n function swapStr(str, first, last){\n return str.substr(0, first)\n + str[last]\n + str.substring(first+1, last)\n + str[first]\n + str.substr(last+1);\n }\n \n while (left < right) {\n let l = left, r = right;\n \n while (s[l] != s[r]) {\n r--;\n }\n \n if (l == r) {\n ans++;\n s = swapStr(s, r, r+1);\n continue;\n } else {\n while (r < right) {\n s = swapStr(s, r, r+1);\n ans++;\n r++;\n } \n }\n left++;\n right--;\n }\n \n return ans;\n};\n``` | 1 | 0 | ['Two Pointers', 'String', 'Greedy', 'JavaScript'] | 0 |
minimum-number-of-moves-to-make-palindrome | C++,Simple brute force two pointers | csimple-brute-force-two-pointers-by-fors-lqzz | ```\nclass Solution {\npublic: \n int minMovesToMakePalindrome(string s) {\n int n = s.length();\n int count = 0;\n int left = 0;\n | forsakencode | NORMAL | 2022-03-05T18:22:45.770145+00:00 | 2022-03-05T18:22:45.770195+00:00 | 163 | false | ```\nclass Solution {\npublic: \n int minMovesToMakePalindrome(string s) {\n int n = s.length();\n int count = 0;\n int left = 0;\n int right = n - 1;\n while(left < right)\n {\n int tl = right,tr = left,c1 = 0,c2 = 0;\n while(s[left]!=s[tl])\n {\n tl--;\n c1++;\n }\n while(s[right]!=s[tr])\n {\n tr++;\n c2++;\n }\n if(c1 > c2)\n {\n for(int i=tr;i>left;i--)\n {\n swap(s[i],s[i-1]);\n }\n count += c2;\n }\n else\n {\n for(int i=tl;i<right;i++)\n {\n swap(s[i],s[i+1]);\n }\n count += c1;\n }\n left++;\n right--;\n }\n return count;\n }\n}; | 1 | 0 | ['Two Pointers', 'C'] | 0 |
minimum-number-of-moves-to-make-palindrome | Python - simple | python-simple-by-ante-krpm | Old school grinding:\n\nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n s,N = list(s), len(s)\n min_swaps = i = 0\n | Ante_ | NORMAL | 2022-03-05T16:30:09.160107+00:00 | 2022-03-05T18:40:00.434406+00:00 | 357 | false | Old school grinding:\n```\nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n s,N = list(s), len(s)\n min_swaps = i = 0\n while i < N // 2:\n L, R = i, N - i - 1\n while L < R:\n if s[L] == s[R]: break\n else: R -= 1\n if L == R:\n s[L], s[L + 1] = s[L + 1], s[L]\n min_swaps += 1\n else:\n for j in range(R, N - L - 1):\n s[j], s[j + 1] = s[j + 1], s[j]\n min_swaps += 1\n i += 1\n return min_swaps\n```\nGreedy everyone else used\n```\nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n s, min_swaps = list(s), 0\n \n while s:\n first_occur_index = s.index(s[-1])\n if first_occur_index == len(s) - 1:\n min_swaps += first_occur_index // 2\n else:\n min_swaps += first_occur_index\n s.pop(first_occur_index)\n \n s.pop()\n \n return min_swaps\n``` | 1 | 0 | [] | 0 |
minimum-number-of-moves-to-make-palindrome | C++ Two pointers greedy algo O(N^2) | c-two-pointers-greedy-algo-on2-by-cqbaoy-3rfz | The idea is to consider two pointers, from left end and right end, to the middle.\nWhenever there is a pair of the same letters, swap the right one towards the | cqbaoyi | NORMAL | 2022-03-05T16:15:03.633887+00:00 | 2022-03-05T16:18:44.384463+00:00 | 270 | false | The idea is to consider two pointers, from left end and right end, to the middle.\nWhenever there is a pair of the same letters, swap the right one towards the right end till it finds the correct position.\nA special condition is that there might be a single letter on the left, which does not find its counterpart on the right. In this case, this letter should be moved to the middle.\n\nOne might wonder why we need to operate on the right one, but not the left one. It is equivalent to operate on the left one, and might result in a different result string though.\n\nTime complexity `O(N^2)`\n```\n int minMovesToMakePalindrome(string s) {\n int n = s.size(), res = 0, i = 0;\n while(i < n / 2)\n {\n int l = i, r = n - l - 1;\n while(l < r)\n {\n if (s[l] == s[r])\n break;\n --r;\n }\n if (l == r)\n {\n\t\t\t\t// There is a single letter which should go to the middle.\n swap(s[l], s[l + 1]);\n ++res;\n }\n else\n {\n\t\t\t\t// Move the letter to the right till its correct position.\n for (int j = r; j < n - l - 1; ++j)\n {\n swap(s[j], s[j + 1]);\n ++res;\n }\n ++i;\n }\n }\n return res;\n }\n``` | 1 | 0 | ['Greedy', 'C'] | 0 |
minimum-number-of-moves-to-make-palindrome | O(n^2) solution || greedy approach || c++ | on2-solution-greedy-approach-c-by-ashish-9oha | \tclass Solution {\n\tpublic:\n\n\n\t\tint minMovesToMakePalindrome(string s) {\n\t\t\tint n = s.size();\n\t\t\tint i=0;\n\t\t\tint j= n-1;\n\t\t\tint ans = 0;\ | ashish_nsut | NORMAL | 2022-03-05T16:12:25.259804+00:00 | 2022-03-05T16:13:03.030655+00:00 | 389 | false | \tclass Solution {\n\tpublic:\n\n\n\t\tint minMovesToMakePalindrome(string s) {\n\t\t\tint n = s.size();\n\t\t\tint i=0;\n\t\t\tint j= n-1;\n\t\t\tint ans = 0;\n\t\t\twhile(i <= j){\n\t\t\t\tif(s[i] == s[j]){\n\t\t\t\t\ti++;\n\t\t\t\t\tj--;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tint idx1 = -1;\n\t\t\t\t\tint idx2 = -1;\n\t\t\t\t\tfor(int k=i+1; k<j; k++){\n\t\t\t\t\t\tif(s[k] == s[j]) {\n\t\t\t\t\t\t\tidx1 = k;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfor(int k=j-1; k>i; k--){\n\t\t\t\t\t\tif(s[k] == s[i]){\n\t\t\t\t\t\t\tidx2 = k;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif(idx1 != -1 && abs(idx1 - i) < abs(idx2 - j)){\n\t\t\t\t\t\tans += abs(idx1 - i);\n\n\t\t\t\t\t\tfor(int k = idx1; k>i; k--){\n\t\t\t\t\t\t\tswap(s[k], s[k-1]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}else{\n\t\t\t\t\t\tans += abs(idx2 - j);\n\t\t\t\t\t\tfor(int k=idx2; k<j; k++){\n\t\t\t\t\t\t\tswap(s[k], s[k+1]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t\tj--;\n\t\t\t}\n\t\t\treturn ans;\n\t\t}\n\t}; | 1 | 0 | [] | 0 |
minimum-number-of-moves-to-make-palindrome | Python | Greedy Easy and Clean Solution | python-greedy-easy-and-clean-solution-by-wmj8 | \nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n s = list(s)\n n = len(s)\n left, right = 0, n-1\n res = | aryonbe | NORMAL | 2022-03-05T16:10:49.216312+00:00 | 2022-04-23T13:22:20.988632+00:00 | 346 | false | ```\nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n s = list(s)\n n = len(s)\n left, right = 0, n-1\n res = 0\n while left < right:\n if s[left] != s[right]:\n lidx, ridx = left+1, right-1\n rdelta = 1\n while s[left] != s[ridx]:\n ridx -= 1\n rdelta += 1\n ldelta = 1\n while s[right] != s[lidx]:\n lidx += 1\n ldelta += 1\n if ldelta < rdelta:\n for i in range(lidx,left,-1):\n s[i-1],s[i] = s[i],s[i-1]\n res += ldelta\n else:\n for i in range(ridx,right):\n s[i],s[i+1] = s[i+1],s[i]\n res += rdelta\n left += 1\n right -= 1\n return res\n``` | 1 | 0 | ['Greedy', 'Python'] | 0 |
minimum-number-of-moves-to-make-palindrome | Two pointers, explained | two-pointers-explained-by-sebnyberg-gkmz | Use a left pointer l and right pointer r.\n\nEach iteration we move both pointers one step inwards.\n\nIf s[l] == s[r], then continue.\n\nIf s[l] != s[r], then | sebnyberg | NORMAL | 2022-03-05T16:07:37.389752+00:00 | 2022-03-05T16:34:10.935628+00:00 | 224 | false | Use a left pointer `l` and right pointer `r`.\n\nEach iteration we move both pointers one step inwards.\n\nIf `s[l] == s[r]`, then continue.\n\nIf `s[l] != s[r]`, then some number of swaps must happen to bring the right character in place.\n\nHow do we know that there isn\'t some other character that is not in the first or last position that is optimal?\n\nWell, wherever that character may be, it must be *inside* the interval`[l,r]`. \nAlso, it must have a matching (or be the odd one out), and that matching is also *inside* `[l,r]`.\nMatching the character later must therefore be better than swapping the character out towards `l`, and `r`\n\n```go\nfunc minMovesToMakePalindrome(s string) int {\n\tn := len(s)\n\tbs := []byte(s)\n\tvar swaps int\n\tfor l, r := 0, n-1; l < r; l, r = l+1, r-1 {\n\t\tif bs[l] == bs[r] {\n\t\t\tcontinue\n\t\t}\n\t\t// ll is l\'s closest counterpart on the right side\n\t\tvar ll int\n\t\tfor ll = r; ll > l && bs[ll] != bs[l]; ll-- {\n\t\t}\n\t\t// rr is r\'s closest counterpart on the left side\n\t\tvar rr int\n\t\tfor rr = l; rr < r && bs[rr] != bs[r]; rr++ {\n\t\t}\n\t\tif r-ll < rr-l {\n\t\t\t// Keep bs[l], move bs[ll] into position\n\t\t\tswaps += r - ll\n\t\t\tcopy(bs[ll:], bs[ll+1:])\n\t\t} else {\n\t\t\t// Keep bs[r], move bs[rr] into position\n\t\t\tswaps += rr - l\n\t\t\tcopy(bs[1:], bs[:rr])\n\t\t}\n\t}\n\n\treturn swaps\n}\n```\n | 1 | 0 | ['Go'] | 1 |
minimum-number-of-moves-to-make-palindrome | EXPLAINED || TWO POINTER || CPP SOLUTION | explained-two-pointer-cpp-solution-by-dd-lvuv | \n// TWO- POINTER APPROACH\n\n// 1. traversed from the two ends and chose the best possible option out of the characters which has its count left greater than | dd_07 | NORMAL | 2022-03-05T16:06:18.738394+00:00 | 2022-03-05T16:13:19.567485+00:00 | 323 | false | ```\n// TWO- POINTER APPROACH\n\n// 1. traversed from the two ends and chose the best possible option out of the characters which has its count left greater than equal to 2 \n\n// 2. calculated the no. of swaps\n\n// Please do upvote if u like my solution\n\nclass Solution {\npublic:\n #define ll int\n int minMovesToMakePalindrome(string s) {\n ll i=0,j=s.length()-1;\n map<char,ll>m;\n for(ll i=0;i<s.length();i++){\n m[s[i]]++;\n }\n ll ans=0;\n ll n=s.length()/2;\n while(i<n){\n ll i1=-1,i2=-1;ll c=INT_MAX;\n for(auto x:m){\n if(x.second>=2){\n ll a=-1,b=-1;\n for(ll z=i;z<s.length();z++){\n if(s[z]==x.first){a=z; break;}\n }\n for(ll z=j;z>=0;z--){\n if(s[z]==x.first){b=z; break;}\n }\n if(abs(a-i)+abs(j-b)<c){i1=a; i2=b; c=(a-i)+(j-b);}\n }\n }\n m[s[i1]]--; m[s[i1]]--;\n while(i1>i){\n //cout<<i1<<" ";\n swap(s[i1],s[i1-1]);\n i1--;\n ans++;\n }\n cout<<endl;\n while(i2<j){\n // cout<<i2<<" ";\n swap(s[i2],s[i2+1]);\n i2++;\n ans++;\n }\n i++; j--;\n }\n //cout<<s<<endl;\n return ans;\n }\n};\n``` | 1 | 0 | ['Two Pointers', 'C++'] | 0 |
minimum-number-of-moves-to-make-palindrome | python solution | python-solution-by-lokeshrai-ig1m | \nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n s = [i for i in s]\n start = 0\n end = len(s)-1\n count | lokeshrai | NORMAL | 2022-03-05T16:04:14.684758+00:00 | 2022-03-05T16:04:14.684786+00:00 | 430 | false | ```\nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n s = [i for i in s]\n start = 0\n end = len(s)-1\n count = 0\n while start < end:\n if s[start] != s[end]:\n i = start\n j = end\n j_f = i_f = False\n ii = jj = -1\n while i < end:\n if s[start] == s[j]:\n j_f = True\n jj = j\n break\n elif s[end] == s[i]:\n i_f = True\n ii = i\n break\n count += 1\n i += 1\n j -= 1\n if i_f:\n for i in range(ii, start, -1):\n s[i] = s[i-1]\n else:\n for i in range(jj, end):\n s[i] = s[i+1]\n start += 1\n end -= 1\n return count\n``` | 1 | 0 | ['Python'] | 0 |
minimum-number-of-moves-to-make-palindrome | Intutive C++ Solution | intutive-c-solution-by-rattanankit2004-250k | Code | rattanankit2004 | NORMAL | 2025-03-19T14:22:33.491749+00:00 | 2025-03-19T14:22:33.491749+00:00 | 3 | false |
# Code
```cpp []
class Solution {
public:
int minMovesToMakePalindrome(string s) {
int n = s.size();
int i = 0; int j =n-1;
int ans = 0;
while(i < j){
if(s[i] == s[j]){
i++;j--;
}
else{
int k = j;
while(k > i && s[i]!=s[k]){
k--;
}
if(k == i){
swap(s[i], s[i+1]);
ans++;
}
else{
for(int l = k; l<j; l++){
swap(s[l], s[l+1]); ans++;
}
i++;j--;
}
}
}
return ans;
}
};
``` | 0 | 0 | ['C++'] | 0 |
minimum-number-of-moves-to-make-palindrome | python | python-by-mykono-762k | Code | Mykono | NORMAL | 2025-03-02T20:27:40.944063+00:00 | 2025-03-02T20:27:40.944063+00:00 | 9 | false | # Code
```python3 []
class Solution:
def minMovesToMakePalindrome(self, s):
s = list(s)
res = 0
while s:
i = s.index(s[-1])
if i == len(s) - 1:
res += i // 2
else:
res += i
s.pop(i)
s.pop()
return res
``` | 0 | 0 | ['Python3'] | 0 |
minimum-number-of-moves-to-make-palindrome | Minimum moves to make the string palindrome | minimum-moves-to-make-the-string-palindr-sfl0 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | RODES | NORMAL | 2025-03-02T10:45:20.115053+00:00 | 2025-03-02T10:45:20.115053+00:00 | 4 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int minMovesToMakePalindrome(string s) {
// we will keep left half same and try to make rifht half equal to left half
int lt=0,rt=s.size()-1;
int ans=0;
while(lt<rt){
int l=lt,r=rt;
while(s[l]!=s[r])r--;
if(l==r){//this is the case abb aurr hum r,a pee phunch gyaa means jiskee baababr karnaa chantee thee whii wala mil gyaa
swap(s[r],s[r+1]);
ans++;
continue;
}else{
while(r<rt){
// case aabb tho r index 1 pe hai
swap(s[r],s[r+1]);
r++;
ans++;
}
lt++;
rt--;
}
}
return ans;
}
};
``` | 0 | 0 | ['C++'] | 0 |
minimum-number-of-moves-to-make-palindrome | greedy + two pointer in c++ 🙃 | greedy-two-pointer-in-c-by-yueyingyang-w0wb | Intuitioni think we need to memorize the -1 situation, which is odd_cnt >= 2.then for the two pointer, find the number that equals to the nums[i] from the right | yueyingyang | NORMAL | 2025-02-24T00:56:40.528069+00:00 | 2025-02-24T00:56:40.528069+00:00 | 4 | false | # Intuition
i think we need to memorize the -1 situation, which is odd_cnt >= 2.
then for the two pointer, find the number that equals to the nums[i] from the right, swap one by one to the left.
if nums[i] is of odd count, swap to the right by 1 to leave it in the middle in the end.
failed for the test case "skwhhaaunskegmdtutlgtteunmuuludii" at first, bc in my code, it will still cnt++ if i == j. hard to debug ;)
# Approach
so called "greedy", but i never understand greedy i think.
they looks always pretty random methods to me.
# Complexity
- Time complexity:
O(N*N) for the worst case.
- Space complexity:
O(1)
# Code
```cpp []
class Solution {
public:
void swap(string& s, int i, int j) {
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
int minMovesToMakePalindrome(string s) {
std::map<char, int> freq;
for (int i = 0; i < s.size(); i++) {
freq[s[i]]++;
}
int odd_cnt = 0;
for (std::pair<char, int> p : freq) {
if (p.second != 0 && p.second % 2 == 1) {
odd_cnt++;
}
}
if (odd_cnt >= 2) return -1;
int i = 0, j = s.size() -1;
int swap_cnt = 0;
while (i < j) {
if (swap_cnt ==163) {
std::cout << "1";
}
while (i < j && s[i] == s[j]) {
i++;
j--;
}
if (i == j) break;
int matched_idx = j;
while (s[matched_idx] != s[i]) {
matched_idx--;
}
if (matched_idx == i) {
std::swap(s[matched_idx], s[matched_idx+1]);
swap_cnt++;
} else {
while (matched_idx < j) {
std::swap(s[matched_idx], s[matched_idx+1]);
matched_idx++;
swap_cnt++;
}
j--;
i++;
}
}
return swap_cnt;
}
};
``` | 0 | 0 | ['C++'] | 0 |
minimum-number-of-moves-to-make-palindrome | Golang, Greedy two pointers | golang-greedy-two-pointers-by-mikyasalem-ezqy | IntuitionFocus on a single rune and attempt to swap adjacent ones until it forms a palindrome.Ex: aabb, the first a and the last b must be same, fix a and try t | mikyasalemayehu1 | NORMAL | 2025-02-15T18:09:02.151462+00:00 | 2025-02-15T18:09:02.151462+00:00 | 4 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Focus on a single rune and attempt to swap adjacent ones until it forms a palindrome.
Ex: **aabb**, the first **a** and the last **b** must be same, fix a and try to change the last b to a by swaping adjecents (count every swap opperation). After that move the left and righ pointers and repet the process.
Note: fixing the left pointer value and trying to change the right pointer value will not always get us to the result, for example **baa**. To cover this case if we can not find solution by fixing the left pointer value we try to fix the right pointer value and swap to the left to change the left pointer value.
# Approach
<!-- Describe your approach to solving the problem. -->
Greedy, try to solve local problem which lead to global solution.
# Complexity
- Time complexity: O(n2)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(n) just for converting the string to []rune so that it can be manipulated in place.
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```golang []
func minMovesToMakePalindrome(s string) int {
moves := 0
input := []rune(s)
l := 0
r := len(input) - 1
for r > l {
if input[l] != input[r] {
got_sol := false
for i := r-1; i > l; i-- {
if input[i] == input[l] {
// swap
for j := i; j < r; j++ {
temp := input[j]
input[j] = input[j+1]
input[j+1] = temp
moves += 1
}
got_sol = true
break
}
}
if !got_sol {
for i := l+1; i < r; i++ {
if input[i] == input[r] {
for j := i; j > l; j-- {
temp := input[j]
input[j] = input[j-1]
input[j-1] = temp
moves += 1
}
got_sol = true
break
}
}
}
}
l += 1
r -= 1
}
return moves
}
``` | 0 | 0 | ['Two Pointers', 'Greedy', 'Go'] | 0 |
minimum-number-of-moves-to-make-palindrome | [python3] 2 pointers time: O(n) space: O(1) | python3-2-pointers-time-on-space-o1-by-t-3hjf | ApproachFind a matching character for s[l] from right side by searching backward.
If a match is found, swap it step by step to bring it to right, counting swaps | Tianze_Kang | NORMAL | 2025-02-11T01:25:51.830251+00:00 | 2025-02-11T01:25:51.830251+00:00 | 37 | false | # Approach
<!-- Describe your approach to solving the problem. -->
Find a matching character for s[l] from right side by searching backward.
If a match is found, swap it step by step to bring it to right, counting swaps.
If no match is found (s[l] appears only once), move it one step right to push it toward the center.
Repeat until left meets right, minimizing swaps needed to form a palindrome.
# Complexity
- Time complexity: O(n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def minMovesToMakePalindrome(self, s: str) -> int:
s = list(s)
l, r = 0, len(s) - 1
res = 0
while l < r:
if s[l] == s[r]:
r -= 1
l += 1
else:
p = r
while p > l and s[p] != s[l]:
p -= 1
if p == l:
s[l], s[l + 1] = s[l + 1], s[l]
res += 1
else:
while p < r:
s[p], s[p + 1] = s[p + 1], s[p]
res += 1
p += 1
r -= 1
l += 1
return res
``` | 0 | 0 | ['Python3'] | 0 |
minimum-number-of-moves-to-make-palindrome | JavaScript solution | javascript-solution-by-janhaviii-vfdc | Approach
If the characters at the left and right positions match, move both pointers inward.
If they don't match:
Search for the closest character from the rig | janhaviii | NORMAL | 2025-02-07T13:37:19.992454+00:00 | 2025-02-07T13:37:19.992454+00:00 | 11 | false | # Approach
1. If the characters at the left and right positions match, move both pointers inward.
2. If they don't match:
- Search for the closest character from the right side that matches the character at arr[left].
- If no match is found (i.e., arr[left] is the last occurrence), swap arr[left] with the adjacent character.
- Otherwise, move the matched character to the correct position by swapping it towards right.
3. Count the swaps:
- Every time a swap occurs, increment the moves counter.
# Complexity
- Time complexity: O(n)
- Space complexity: O(n)
# Code
```javascript []
var minMovesToMakePalindrome = function(s) {
const n = s.length;
let moves = 0, left = 0, right = n - 1;;
let arr = s.split('');
while (left < right) {
if (arr[left] === arr[right]) {
left++;
right--;
} else {
let l = left, r = right;
while (arr[r] !== arr[left] && r > left) {
r--;
}
if (r === left) {
[arr[left], arr[left + 1]] = [arr[left + 1], arr[left]];
moves++;
} else {
while (r < right) {
[arr[r], arr[r + 1]] = [arr[r + 1], arr[r]];
moves++;
r++;
}
left++;
right--;
}
}
}
return moves;
};
``` | 0 | 0 | ['Two Pointers', 'String', 'Greedy', 'JavaScript'] | 0 |
minimum-number-of-moves-to-make-palindrome | c++ easy solution | c-easy-solution-by-daniux-7g7g | IntuitionApproachComplexity
Time complexity: O(n^2)
Space complexity: o(n)
Code | daniux | NORMAL | 2025-01-28T00:25:09.015388+00:00 | 2025-01-28T00:25:09.015388+00:00 | 6 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: O(n^2)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: o(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int minMovesToMakePalindrome(string s) {
vector<char> cset;
for(char c:s){
cset.push_back(c);
}
int res=0;
while(!cset.empty()){
char last=cset.back();
//find the first occurance
auto first=find(cset.begin(),cset.end(),last);
int idx=distance(cset.begin(),first);
if(idx==cset.size()-1){
res+= cset.size()/2;
}else {
res += idx;
cset.erase(first);
}
cset.pop_back();
}
return res;
}
};
``` | 0 | 0 | ['C++'] | 0 |
minimum-number-of-moves-to-make-palindrome | 2193. Minimum Number of Moves to Make Palindrome | 2193-minimum-number-of-moves-to-make-pal-jtue | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | G8xd0QPqTy | NORMAL | 2025-01-18T05:00:55.556881+00:00 | 2025-01-18T05:00:55.556881+00:00 | 10 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int minMovesToMakePalindrome(string input) {
int totalMoves = 0;
while (!input.empty()) {
char lastCharacter = input.back();
int position = input.find(lastCharacter);
if (position == input.size() - 1) {
totalMoves += position / 2;
} else {
totalMoves += position;
input.erase(position, 1);
}
input.pop_back();
}
return totalMoves;
}
};
auto optimizeIO = []() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); return 0; }();
``` | 0 | 0 | ['C++'] | 0 |
minimum-number-of-moves-to-make-palindrome | BIT explanation | bit-explanation-by-dnanper-7h9l | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | dnanper | NORMAL | 2025-01-13T03:20:32.168814+00:00 | 2025-01-13T03:20:32.168814+00:00 | 7 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
// BIT[i] stores the difference between the start of the sequence and the current position i.
// We observe that when swapping begin() with i, all elements from begin() to i-1
// are shifted one position to the right, while the start of the sequence itself
// shifts up by one position as it completes the matching of the current start-end pair.
// Thus, the relative position of all elements from begin() to i-1
// compared to begin() remains unchanged (since both are shifted by 1).
//
// On the other hand, elements from i onward are not affected by the swap
// in terms of their positions. Therefore, their relative position
// compared to begin() decreases by 1.
//
// In summary, BIT[i] stores the decrease in the relative position of i
// compared to begin(), starting at 0. With each swap, the decrease
// for elements after i increases by 1 unit.
int n;
int minMovesToMakePalindrome(string s)
{
n = s.size();
BIT = vector<int> (n+1, 0);
int res = 0;
vector<deque<int>> pos(26);
for (int i = 0; i < s.size(); i++) pos[s[i]-'a'].push_back(i);
for (int i = s.size()-1; i >= 0; i--)
{
int cur = s[i]-'a';
// this case only exist when we finish the first half, mean that all the string
// is done
if (pos[cur].empty()) continue;
int ans = pos[cur].front() - prefixSum(pos[cur].front());
add(pos[cur].front()+1, 1);
if (pos[cur].size() > 1) pos[cur].pop_front();
else ans = ans/2;
res += ans;
pos[cur].pop_back();
}
return res;
}
private:
vector<int> BIT;
int prefixSum(int i)
{
int sum = 0;
for (i = i + 1; i > 0; i -= i & (-i))
sum += BIT[i];
return sum;
}
void add(int i, int val)
{
for (i = i + 1; i <= n; i += i & (-i))
BIT[i] += val;
}
};
``` | 0 | 0 | ['C++'] | 0 |
minimum-number-of-moves-to-make-palindrome | Python (simple greedy) - Explained | python-simple-greedy-explained-by-khlie8-vkll | IntuitionExplaining
https://leetcode.com/problems/minimum-number-of-moves-to-make-palindrome/solutions/5197436/python-simple-greedyApproachComplexity
Time compl | khlie87 | NORMAL | 2025-01-04T16:32:56.882047+00:00 | 2025-01-04T16:32:56.882047+00:00 | 38 | false | # Intuition
Explaining
https://leetcode.com/problems/minimum-number-of-moves-to-make-palindrome/solutions/5197436/python-simple-greedy
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def minMovesToMakePalindrome(self, s: str) -> int:
count, arr = 0, list(s)
while arr:
# get first occuring index of last char
i = arr.index(arr[-1])
if i == len(arr)-1:
# this is the only occurence
# (first occurence of last char is the last char)
# (can only happen at most once, since we are guaranteed to be able to make a palindrome)
# count moves to place in the middle
count += i//2
else:
# i moves to place this char on the left side
count += i
# remove this value from the list
arr.pop(i)
# remove the last char from list
arr.pop()
return count
``` | 0 | 0 | ['Python3'] | 0 |
minimum-number-of-moves-to-make-palindrome | Kotlin Two Pointer Approach | kotlin-two-pointer-approach-by-yadunath-f200 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | yadunath | NORMAL | 2024-12-16T15:53:37.592850+00:00 | 2024-12-16T15:53:37.592850+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```kotlin []\nclass Solution {\n fun minMovesToMakePalindrome(str: String): Int {\n val chars = str.toCharArray()\n var left = 0\n var right = chars.size - 1\n var swaps = 0\n\n while (left < right) {\n if (chars[left] == chars[right]) {\n left++\n right--\n } else {\n var k = right\n while(k > left && chars[left] != chars[k]){\n k--\n }\n\n if(k == left){\n swap(left, left + 1, chars)\n swaps++\n }else{\n for(i in k until right){\n swap(i, i + 1, chars)\n swaps++\n }\n left++\n right--\n }\n }\n }\n\n return swaps\n }\n\n fun swap(left:Int,right: Int,chars:CharArray){\n\n val temp = chars[left]\n chars[left] = chars[right]\n chars[right] =temp\n }\n}\n``` | 0 | 0 | ['Kotlin'] | 0 |
minimum-number-of-moves-to-make-palindrome | Kotlin Two Pointer Approach | kotlin-two-pointer-approach-by-yadunath-e52v | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | yadunath | NORMAL | 2024-12-16T15:53:34.823522+00:00 | 2024-12-16T15:53:34.823522+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```kotlin []\nclass Solution {\n fun minMovesToMakePalindrome(str: String): Int {\n val chars = str.toCharArray()\n var left = 0\n var right = chars.size - 1\n var swaps = 0\n\n while (left < right) {\n if (chars[left] == chars[right]) {\n left++\n right--\n } else {\n var k = right\n while(k > left && chars[left] != chars[k]){\n k--\n }\n\n if(k == left){\n swap(left, left + 1, chars)\n swaps++\n }else{\n for(i in k until right){\n swap(i, i + 1, chars)\n swaps++\n }\n left++\n right--\n }\n }\n }\n\n return swaps\n }\n\n fun swap(left:Int,right: Int,chars:CharArray){\n\n val temp = chars[left]\n chars[left] = chars[right]\n chars[right] =temp\n }\n}\n``` | 0 | 0 | ['Kotlin'] | 0 |
minimum-number-of-moves-to-make-palindrome | [Rust] Two pointer solution | rust-two-pointer-solution-by-dinotroll-chdd | IntuitionApproachComplexity
Time complexity:
O(n2)
Space complexity:
O(n)CodeIt beat 100% space and time...If that matters to anyone. | dinotroll | NORMAL | 2024-12-15T14:05:53.557921+00:00 | 2024-12-15T14:05:53.557921+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n^2)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n# Code\nIt beat 100% space and time...If that matters to anyone.\n```rust []\nimpl Solution {\n fn swaps_made_forward(char_vec: &mut Vec<char>, start: usize, end: usize) -> i32 {\n let mut moves: i32 = 0;\n let (mut s, mut e): (usize, usize) = (start, end);\n while s < e {\n char_vec.swap(s, s + 1);\n s += 1;\n moves += 1;\n }\n moves\n }\n\n pub fn min_moves_to_make_palindrome(s: String) -> i32 {\n let mut char_vec: Vec<char> = s.chars().collect();\n let mut moves: i32 = 0;\n let (mut start, mut end): (usize, usize) = (0, s.len() - 1);\n\n while start < end {\n let (mut start_c, mut end_c): (char, char) = (char_vec[start], char_vec[end]);\n\n if start_c != end_c {\n let mut curr: usize = end - 1;\n\n while curr > start {\n let curr_c: char = char_vec[curr];\n if curr_c == start_c {\n moves += Self::swaps_made_forward(&mut char_vec, curr, end);\n end -= 1;\n break;\n }\n curr -= 1;\n }\n\n if curr == start {\n let mut mid: usize = s.len() / 2;\n moves += (mid - start) as i32;\n }\n } else {\n end -= 1;\n }\n start += 1;\n }\n\n moves\n }\n}\n``` | 0 | 0 | ['Rust'] | 0 |
minimum-number-of-moves-to-make-palindrome | Two Pointers - Golang Solution | two-pointers-golang-solution-by-sukratia-mwy5 | Intuition\nThe problem involves rearranging a string to form a palindrome with the minimum number of adjacent swaps. A palindrome reads the same forwards and ba | sukratiagrawal192 | NORMAL | 2024-12-04T18:43:36.121406+00:00 | 2024-12-04T18:43:36.121485+00:00 | 6 | false | # Intuition\nThe problem involves rearranging a string to form a palindrome with the minimum number of adjacent swaps. A palindrome reads the same forwards and backwards, so the characters in the string need to have symmetrical placements around the center.\n\nTo solve this:\n- Focus on matching characters from both ends of the string while minimizing swaps.\n- If the characters at the current ends don\u2019t match, we need to find their correct pairs within the string and swap them into position.\n\n# Approach\n1. Two-Pointer Technique:\nUse two pointers, start at the beginning and end at the end of the string, to traverse inward.\n\n2. Check Characters\n- If s[start] matches s[end], move both pointers inward.\n- If they don\u2019t match, determine the closer optimal swap direction:\n - Find the nearest matching character to s[start] from end moving left (currEnd).\n - Find the nearest matching character to s[end] from start moving right (currStart).\n\n3. Optimal Swap Strategy:\n- Compare the distances of currStart and currEnd to decide which direction requires fewer swaps.\n- Perform adjacent swaps to move the matching character into the correct position.\n- Update the string after each swap and increment the moves counter.\n\n4. Repeat:\nContinue this process until all characters are correctly placed.\n\n# Complexity\n- Time complexity:\n - For each unmatched pair, the algorithm scans up to O(n) characters to find the closest match, performing O(n) swaps in the worst case\n - Overall: O(n^2).\n\n- Space complexity:\n - The algorithm modifies the string in place using a byte slice, requiring O(n) space for string conversion.\n - Additional storage for a few variables is O(1).\n - Overall: O(n)\n\n# Code\n```golang []\nfunc minMovesToMakePalindrome(s string) int {\n start,end:=0,len(s)-1\n moves:=0\n for start<end{\n if s[start]!=s[end]{\n currEnd:=end\n for s[start]!=s[currEnd]{\n currEnd--\n }\n currStart:=start\n for s[currStart]!=s[end]{\n currStart++\n }\n if currStart-start>end-currEnd{\n str:=[]byte(s)\n for currEnd<end{\n moves++\n str[currEnd],str[currEnd+1]=str[currEnd+1],str[currEnd]\n currEnd++\n }\n s=string(str)\n } else{\n str:=[]byte(s)\n for start<currStart{\n moves++\n str[currStart],str[currStart-1]=str[currStart-1],str[currStart]\n currStart--\n }\n s=string(str)\n }\n }\n start++\n end--\n }\n return moves\n}\n``` | 0 | 0 | ['Two Pointers', 'Go'] | 0 |
minimum-number-of-moves-to-make-palindrome | C# || Too Much Greedy Approach | c-too-much-greedy-approach-by-sunil20000-o5pi | csharp []\npublic class Solution {\n public int MinMovesToMakePalindrome(string s) {\n int result = 0, n = s.Length;\n List<char> ls = s.ToList | sunil20000 | NORMAL | 2024-11-18T14:03:04.623053+00:00 | 2024-11-18T14:03:04.623100+00:00 | 16 | false | ```csharp []\npublic class Solution {\n public int MinMovesToMakePalindrome(string s) {\n int result = 0, n = s.Length;\n List<char> ls = s.ToList();\n while(ls.Count > 0)\n {\n var lastChar = ls[ls.Count - 1];\n var index = ls.FindIndex( c => c == lastChar);\n\n if(index == ls.Count - 1)\n {\n result += (index / 2);\n }\n else\n {\n result += index;\n ls.RemoveAt(index);\n }\n\n ls.RemoveAt(ls.Count - 1);\n }\n\n return result;\n }\n}\n``` | 0 | 0 | ['Two Pointers', 'Greedy', 'C#'] | 0 |
minimum-number-of-moves-to-make-palindrome | C# || Too Much Greedy Approach | c-too-much-greedy-approach-by-sunil20000-lu14 | csharp []\npublic class Solution {\n public int MinMovesToMakePalindrome(string s) {\n int result = 0, n = s.Length;\n List<char> ls = s.ToList | sunil20000 | NORMAL | 2024-11-18T14:02:28.495046+00:00 | 2024-11-18T14:02:28.495104+00:00 | 12 | false | ```csharp []\npublic class Solution {\n public int MinMovesToMakePalindrome(string s) {\n int result = 0, n = s.Length;\n List<char> ls = s.ToList();\n while(ls.Count > 0)\n {\n var lastChar = ls[ls.Count - 1];\n var index = ls.FindIndex( c => c == lastChar);\n\n if(index == ls.Count - 1)\n {\n result += (index / 2);\n }\n else\n {\n result += index;\n ls.RemoveAt(index);\n }\n\n ls.RemoveAt(ls.Count - 1);\n }\n\n return result;\n }\n}\n``` | 0 | 0 | ['Two Pointers', 'Greedy', 'C#'] | 0 |
minimum-number-of-moves-to-make-palindrome | Java | Two Pointers | Beginner Friendly | Clean code with detailed explanation | java-two-pointers-beginner-friendly-clea-vtwe | Greedy Approach\n\n# Intuition\n\nThe goal of the problem is to transform a given string into a palindrome by using a minimum number of adjacent character swaps | ajay_gaulia23 | NORMAL | 2024-10-24T13:54:48.348077+00:00 | 2024-10-24T13:54:48.348109+00:00 | 19 | false | # Greedy Approach\n\n# Intuition\n\nThe goal of the problem is to transform a given string into a palindrome by using a minimum number of adjacent character swaps. So the approach revolves around making pairs of characters at symmetric positions until the entire string is symmetrical. **The key is to bring matching characters closer to each other using adjacent swaps while minimizing the number of moves.**\n\nThe strategy involves comparing characters at symmetric positions (`left` and `right`) and finding ways to make them equal with minimal swaps. If the characters are already the same, no swaps are needed for that pair. Otherwise, we find the nearest character that matches the opposite end and move it to its desired position.\n\n# Approach\n\n1. **Two Pointers Technique**:\n\n - Use two pointers, `left` and `right`, starting at the beginning (`0`) and end (`n-1`) of the string, respectively.\n - **The goal is to make the characters at `left` and `right` the same by swapping adjacent characters until the string forms a palindrome**.\n\n2. **Finding Matching Characters**:\n\n - If `s.charAt(left)` is equal to `s.charAt(right)`, it means that these two characters are already in the correct position. Move both pointers inward (`left++` and `right--`) to continue with the rest of the string.\n - If they are **not** equal, search for the matching character for `s.charAt(left)` between the positions `left` and `right`.\n\n3. **Helper Method: \\**\\*****`kthIndexOfLeftChar`**:\n\n - The `kthIndexOfLeftChar(String s, int left, int k)` method finds the position `k` of a character starting from the `right` that matches `s.charAt(left)`. **The goal is to locate the closest matching character to `left`.**\n\n4. **Swap Characters Using ************************************************************************************`swapAdjacent`************************************************************************************ Method**:\n\n - If a matching character for `s.charAt(left)` is found at index `k` (`k < right`), move that character to the `right` position by swapping adjacent characters iteratively.\n - The `swapAdjacent(int k, int right, String s)` method takes the character at index `k` and swaps it to the right until it reaches the correct position (`right`). Each swap adds to the `steps` count.\n - If `k == left`, it means there is no matching character for `s.charAt(left)` at `right`. **Since it\'s given in the problem**\xA0**that the input will be generated such that S can always be converted to a palindrome**. **Hence if we couldn\'t find a pair for left character, left character\'s correct position will be at the centre of the palindrome & this scenario will only happen when we have odd length of string.**\xA0\xA0\\\n In this case, swap `s.charAt(left)` with the next adjacent character (`left + 1`) to bring the character closer to its correct position. Eventually this character will move to the middle of the string.\xA0\n\n5. **Update Steps and Continue**:\n\n - After each set of swaps, update the `steps` and the `String s` accordingly to keep track of the total number of moves made to create a palindrome.\n - Repeat the process until the `left` pointer is greater than or equal to the `right` pointer, which means that the entire string has been processed.\n\n# Complexity Analysis\n\n- **Time Complexity**: **O(n^2)**\n\n - In the worst case, each character may need to be swapped up to `n` times. The nested loop in `swapAdjacent` contributes to the quadratic time complexity. Thus, the overall time complexity is **O(n^2)**.\n - The operation involves finding the matching character and then swapping it multiple times until it reaches its correct position, which can result in a high number of operations for long strings.\n\n- **Space Complexity**: **O(n)**\n\n - The space complexity is **O(n)** because we create a new `char[]` array each time we call `swapAdjacent` to perform swaps. **This additional array is used to construct a new `String` in Java, contributing to the space complexity.**\n - The `kthIndexOfLeftChar` and `swapAdjacent` methods use constant space for variables, making their contribution to space complexity negligible compared to the `char[]` array creation.\n\n## Example Walkthrough\n\nConsider the input string `"aabb"`:\n\n1. **Initial State**: `left = 0`, `right = 3`, `steps = 0`.\n - `s.charAt(left) = \'a\'`, `s.charAt(right) = \'b\'`. They are not equal.\n - Find the matching character for `s.charAt(left)` (`\'a\'`) starting from the `right`. The match is found at index `1`.\n2. **Swapping**:\n - Swap the character at index `1` to the `right` position (`right = 3`) using `swapAdjacent`. After the swaps, `s` becomes `"abba"`, and `steps = 2`.\n3. **Continue with Next Pair**:\n - Update `left = 1`, `right = 2`. Now, `s.charAt(left)` is equal to `s.charAt(right)` (`\'b\' == \'b\'`), so move both pointers inward (`left++`, `right--`).\n4. **Termination**:\n - When `left >= right`, the process stops. The total number of steps required is `2`.\n\n\n\n\n# Code\n```java []\nclass Solution {\n\n public int kthIndexOfLeftChar(String s, int left, int k){\n char charAtLeft = s.charAt(left);\n\n /** Moving k to the left, Return as soon as we found the same character */\n while(k > left){\n if(charAtLeft == s.charAt(k))\n return k; \n\n k--; \n }\n\n /** Couldn\'t find a pair for the left char, Hence return left index */\n return left; \n }\n\n public String swapAdjacent(int k, int right, String s){\n\n char[] sChars = s.toCharArray();\n\n /** Move kth character to the right by doing adjacent swaps */ \n while(k<right){\n char temp = sChars[k];\n sChars[k] = sChars[k+1];\n sChars[k+1] = temp ;\n k++; \n } \n\n /** Return the transformed string after swaps */ \n return new String(sChars);\n }\n\n\n\n public int minMovesToMakePalindrome(String s) {\n int n = s.length();\n\n /** Assign two pointers at the edge of string */\n int left = 0; \n int right = n-1; \n\n int steps = 0; \n\n /** Move pointers closer while making the string a pallindrome */\n while(left < right){\n\n /** Characters already matching : No swaps needed, Update the \n pointers & continue */\n if(s.charAt(left) == s.charAt(right)){\n left++; right--; \n continue; \n }\n\n /** Index of other character same as left character */\n int k = kthIndexOfLeftChar(s, left, right);\n \n /** If pair for left character can\'t be found, Means this is a single\n character in the given string, Hence it will be moved to the middle \n eventually. Swap with the next character for now & increment steps by 1 */\n if(k==left){\n steps++;\n s = swapAdjacent(left,left+1,s); \n }else{\n /** Now make swaps to move the character at Kth index to the right\n Include/Add (right-k) swaps for moving k to right position */\n s = swapAdjacent(k,right,s);\n steps += (right-k);\n }\n }\n\n /** Finally retutn the steps count once we break from the loop */\n return steps; \n\n }\n\n}\n``` | 0 | 0 | ['Two Pointers', 'String', 'Greedy', 'Java'] | 0 |
minimum-number-of-moves-to-make-palindrome | Java Beats 90% | java-beats-90-by-lockmyre-mnks | Intuition\nIt\'s greedy so the intuition is that there is no intuition.\n\n# Code\njava []\nclass Solution {\n public int minMovesToMakePalindrome(String s) | lockmyre | NORMAL | 2024-10-19T22:47:47.755861+00:00 | 2024-10-19T22:47:47.755880+00:00 | 14 | false | # Intuition\nIt\'s greedy so the intuition is that there is no intuition.\n\n# Code\n```java []\nclass Solution {\n public int minMovesToMakePalindrome(String s) {\n return findMinMoves(0, s.length() - 1, s.toCharArray());\n }\n\n private int findMinMoves(int lo, int hi, char[] s) {\n if (lo >= hi) return 0;\n if (s[lo] == s[hi])\n return findMinMoves(lo + 1, hi - 1, s);\n\n int nextLo = hi, nextHi = lo;\n while (nextLo > lo && s[nextLo] != s[lo]) nextLo--;\n while (nextHi < hi && s[nextHi] != s[hi]) nextHi++;\n\n if (nextLo != lo) {\n for (int i = nextLo; i < hi; i++)\n swap(s, i, i + 1);\n return (hi - nextLo) + findMinMoves(lo + 1, hi - 1, s);\n } else {\n for (int i = nextHi; i > lo; i--)\n swap(s, i, i - 1);\n return (nextHi - lo) + findMinMoves(lo + 1, hi - 1, s);\n }\n }\n\n private void swap(char[] s, int i, int j) {\n char temp = s[i];\n s[i] = s[j];\n s[j] = temp;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
minimum-number-of-moves-to-make-palindrome | 2193. Minimum Number of Moves to Make Palindrome | TC: O(n^2) for worst case SC: O(1) | 2193-minimum-number-of-moves-to-make-pal-dpuk | \n\n## Intuition\nTo determine the minimum number of moves required to rearrange a string into a palindrome, we can leverage the fact that a palindrome reads th | mukeshbala24 | NORMAL | 2024-10-08T17:21:41.916793+00:00 | 2024-10-08T17:21:41.916833+00:00 | 13 | false | \n\n## Intuition\nTo determine the minimum number of moves required to rearrange a string into a palindrome, we can leverage the fact that a palindrome reads the same forwards and backwards. Therefore, we need to move characters in such a way that each character has a matching counterpart. The key is to identify how many moves are necessary to bring matching characters together.\n\n## Approach\n1. **Identify Matching Characters**: Start by examining the last character of the string. Find the first occurrence of this character (from the start of the string).\n2. **Count Moves**: \n - If the matching character is the last one, it could be the middle character in an odd-length palindrome. We can calculate moves based on its index divided by 2.\n - If it\'s found elsewhere, count the number of moves needed to bring this character to the end and remove it from the current string.\n3. **Repeat**: Continue the process until all characters are matched or the string is empty.\n4. **Return Total Moves**: Finally, return the total number of moves accumulated.\n\n### Code Explanation\n```cpp\nclass Solution {\npublic:\n int minMovesToMakePalindrome(string s) {\n int ans = 0; // Initialize the move counter\n while (s.size()) { // Continue until the string is empty\n int i = s.find(s.back()); // Find the first occurrence of the last character\n if (i == s.size() - 1) {\n ans += i / 2; // If it\'s the last character, add half of its index to moves\n } else {\n ans += i; // Otherwise, add the index to moves\n s.erase(i, 1); // Remove the character from the string\n }\n s.pop_back(); // Remove the last character from the string\n }\n return ans; // Return the total moves\n }\n};\n```\n\n## Complexity\n- **Time Complexity**: \n - The overall time complexity is \\(O(n^2)\\) in the worst case because, for each character, we may need to search through the string to find the matching character.\n \n- **Space Complexity**: \n - The space complexity is \\(O(1)\\) since we are not using any additional data structures that grow with the input size. We are only using a few integer variables for tracking indices and counts.\n\nThis approach efficiently counts the minimum moves needed to form a palindrome by iterating through the string while continuously adjusting its size, leading to a solution that directly addresses the problem. | 0 | 0 | ['Two Pointers', 'String', 'Greedy', 'Binary Indexed Tree', 'C++'] | 0 |
minimum-number-of-moves-to-make-palindrome | Java || Easy to understand || StringBuilder || | java-easy-to-understand-stringbuilder-by-bbwa | Intuition\n Describe your first thoughts on how to solve this problem. \nThink when any string will be the palindrome ???\n\n# Approach\n Describe your approach | yash_pal2907 | NORMAL | 2024-09-01T18:20:36.817130+00:00 | 2024-09-01T18:20:36.817163+00:00 | 8 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThink when any string will be the palindrome ???\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe will use StringBuilder class here to edit/modify the string.\nFirst will check if the last character and first character are matching or not . if matching then remove the both character , no need to swap it.\nIf we have two condition that \n 1. character is present at once - so move it to middle of the string \n 2. else find the first occurance of the character and move to it starting of the string , will give the number of swap required (means delete the character and delete tha last character )\n\n# Complexity\n- Time complexity: O(N^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int minMovesToMakePalindrome(String s) {\n StringBuilder sb = new StringBuilder(s);\n int start = 0 , end = s.length()-1;\n int move = 0;\n\n while(sb.length() >0 ){\n if(sb.charAt(0) == sb.charAt(sb.length()-1)){\n sb.deleteCharAt(0);\n if(sb.length()>=1)\n sb.deleteCharAt(sb.length()-1);\n }else{\n // System.out.println(sb.toString());\n/** pick the last character present in the string and find the first occurance of the character from starting of the string */\n int index = sb.indexOf(sb.substring(sb.length()-1));\n if(index == sb.length()-1){\n move += (sb.length() /2);\n if(sb.length()>=1)\n sb.deleteCharAt(sb.length()-1);\n }else{\n move+= index;\n sb.deleteCharAt(index);\n if(sb.length()>=1)\n sb.deleteCharAt(sb.length()-1);\n \n }\n }\n }\n \n return move;\n }\n}\n``` | 0 | 0 | ['String', 'Greedy', 'Java'] | 0 |
difference-between-maximum-and-minimum-price-sum | Re rooting | O(N) | Explained | re-rooting-on-explained-by-java_programm-xap4 | Rerooting\nIt is a technique where we solve a given problem for all roots.\n\nSteps\n1. Arbitrary root the tree, lets take node 0 for explanation.\n2. Solve t | Java_Programmer_Ketan | NORMAL | 2023-01-15T04:03:46.453216+00:00 | 2023-01-17T17:19:59.806228+00:00 | 9,047 | false | # Rerooting\n*It is a technique where we solve a given problem for all roots.*\n\n**Steps**\n1. Arbitrary root the tree, lets take `node 0` for explanation.\n2. Solve the given problem as if it was rooted at `node 0`.\n3. Similarily solve the problem for all nodes\n\nEven if you have never heard of this term before, no problem it just **DFS**. In this post I will explain how to solve this particular question even if you have never done rerooting before. \n\nIf you want proper resources for learning/reading about re-rooting then refer these. \n1. \t[Re rooting](https://usaco.guide/gold/all-roots?lang=java)\n2. \t[Re rooting section of this book](https://dp-book.com/Dynamic_Programming.pdf)\n\n**Observation**\n* Minimum Path sum is always equal to the value of root node. If we include any other vertex in our path we are going to increase the sum as all weights of nodes to greater than 1.\n* Try to solve a **simpler problem** first. `Given a tree rooted at node 0 where each node has positive weights assigned. Calculate the maximum weight of a path starting from root node. `\n\nI will be using this tree. Note the node labels are node indices and not weights\n\n\n\n\n**Solving Simpler Problem**\nDo you see DP in this ?? \nAt `node 1` we have two choices either take path from `subtree of node 3` or take from `subtree of node 4`. So we will chose the maximum path. Similarily we have 2 choices at `node 0`\n\n```\nint[] subtree_sum = new int[n]; \n//subtree_sum[i] = Maximum path weight starting from node i if the tree was rooted at node 0\n```\n\n```\nsubtree_sum[0] = max(subtree_sum[1],subtree[2]) + price[0];\nsubtree_sum[1] = max(subtree_sum[3],subtree_sum[4]) + price[1];\n```\n\nTo calculate this we will run a dfs to fill subtree_sum. and return subtree_sum[0]\n\nWell done we have solved **2/3** of the problem according to the steps of rerooting. But now comes the main part.\n\n**Solving for all roots**\n Now we want to root the tree at node 1. how can we calculate the maximum path starting from `node 1`. There are two options the path can go to one of the children `3,4` or go to its parent `0`\n* From `subtree_sum` we can find maximum paths in subtree of `3 and 4`.\n* To handle the maximum path from parent we will have a parameter in our dfs function `parent_contribution` which is equal to `price[parent] + max(maximum weighted child of parent, parent\'s parent_contribution).` If the current node is the maximum weight child of parent then we need to chose the second most weighted child of parent. \n* ` Maximum difference at node 1 = max(subtree_sum[3],subtree_sum[4],parent_contribtion) + price[1] - price[1] (minimum path)`\n = ``max(subtree_sum[3],subtree_sum[4],parent_contribtion)``\n\t\t\t\nVisit all vertices in second dfs and find the maximum difference. \n\nTime Complexity O(N)\nSpace Complexity O(N)\n\n```\nclass Solution {\n private long[] subtree_sum; //Stores -> If the tree was rooted at node 0 what is the maximum sum we can get from subtree of i\n private long max_dif = 0L;\n public long maxOutput(int n, int[][] edges, int[] price) {\n List<List<Integer>> tree = new ArrayList<>();\n for(int i=0;i<n;i++) tree.add(new ArrayList<>());\n for(int[] e: edges){\n tree.get(e[0]).add(e[1]);\n tree.get(e[1]).add(e[0]);\n }\n subtree_sum = new long[n];\n dfs(0,-1,tree,price); //Fills the subtree_sum array\n dfs2(0,-1,tree,price,0);\n return max_dif;\n }\n private long dfs(int node, int parent, List<List<Integer>> tree, int[] price){\n long m = 0L; //We need the maximum contribution of children. \n for(int child: tree.get(node)){\n if(child == parent) continue;\n m = Math.max(m, dfs(child,node,tree,price));\n }\n return subtree_sum[node] = price[node] + m;\n }\n private void dfs2(int node, int parent,List<List<Integer>> tree, int[] price, long parent_contribution){\n int c1=-1;\n long mc1=0,mc2=0; //2 maximum contribution of children\n for(int child: tree.get(node)){\n if(child == parent) continue;\n if(subtree_sum[child]>mc1){\n mc2 = mc1;\n c1 = child;\n mc1 = subtree_sum[child];\n }\n else if(subtree_sum[child]>mc2){\n mc2 = subtree_sum[child];\n }\n }\n long path1 = mc1;\n long path2 = parent_contribution;\n max_dif = Math.max(max_dif,Math.max(path1,path2));\n for(int child: tree.get(node)){\n if(child == parent) continue;\n/*\nHow can a parent add a path to child?\n1. Take a path from a siblling of child (we want the maximum siblling)\n2. Take a path from its parent\n\nThus the contribution of current node to its child c is maximum(maximum siblling ,node\'s parent_contribution)\n*/\n if(c1 == child) dfs2(child,node,tree,price,price[node]+Math.max(mc2,parent_contribution)); \n else dfs2(child,node,tree,price,price[node]+Math.max(mc1,parent_contribution));\n }\n }\n}\n```\nFor similar problems have a look at comments\n\n@Leetcode please consider adding a spelling checker for posts.. | 103 | 0 | [] | 21 |
difference-between-maximum-and-minimum-price-sum | C++ DFS | one pass | O(n + edge) | beats 100% | c-dfs-one-pass-on-edge-beats-100-by-jaso-604y | IntuitionThis question is similar to 124. Binary Tree Maximum Path Sum but a little different.The difference between this question and 124 are:
Only positive va | jason7708 | NORMAL | 2023-01-15T05:16:04.600358+00:00 | 2025-01-28T03:29:48.795213+00:00 | 4,797 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
This question is similar to [124. Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/) but a little different.
The difference between this question and 124 are:
1. Only positive values
2. Not a binary tree
3. The answer is not the maximum path but the path that subtracts the smaller endpoint.
Here are some key points to solve this problem :
1. Consider question 124 with only positive nodes :
- The DFS returns the maximum path from the current root to one of the leaf nodes.
- At each subtree, we update the final answer with left subtree return value (which is the max path sum) + current root node value + right subtree return value.
2. We need to consider all subtrees instead of just left and right.
3. Since we don't know which side of endpoint is the minimum we should remove and if the path is still maximum after we remove the endpoint, we maintain another value, which is the path sum from root to leaf but minus its leaf node, and try both two cases.
In the for loop we iterate all subtrees and update the answer with two cases:
1. Maximum path sum from previous subtrees + path sum without leaf node from current subtree
2. Maximum path sum without leaf node from previous subtrees + path sum from current subtree
Design DFS that returns two values:
1. maximum path sum, we call it `max_w_leaf` (maximum with leaf)
2. maximum (path sum - leaf node), we call it `max_wo_leaf` (maximum without leaf)
# Complexity
- Time complexity: $$O(n + edge)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(n + edge)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```
class Solution {
public:
long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {
vector<vector<int>> graph(n);
for(const auto& edge : edges) {
graph[edge[0]].push_back(edge[1]);
graph[edge[1]].push_back(edge[0]);
}
long long ans = 0LL;
auto dfs = [&] (this auto&& dfs, int cur, int pre) -> pair<long long, long long> {
long long max_w_leaf = price[cur], max_wo_leaf = 0LL;
for(const auto node : graph[cur]) {
if(node != pre) {
auto&& [w_leaf, wo_leaf] = dfs(node, cur);
ans = max(ans, max(max_w_leaf + wo_leaf, max_wo_leaf + w_leaf));
max_w_leaf = max(max_w_leaf, w_leaf + price[cur]);
max_wo_leaf = max(max_wo_leaf, wo_leaf + price[cur]);
}
}
return { max_w_leaf, max_wo_leaf };
};
dfs(0, -1);
return ans;
}
};
``` | 69 | 0 | ['C++'] | 11 |
difference-between-maximum-and-minimum-price-sum | ✅ Very Simple Python DFS | very-simple-python-dfs-by-0xsapra-lp23 | \nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n """\n greedy way could be try each node | 0xsapra | NORMAL | 2023-01-15T04:29:54.876480+00:00 | 2023-01-15T05:13:42.115059+00:00 | 2,632 | false | ```\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n """\n greedy way could be try each node as root, but it will be:\n O(N * N) \n \n we can use DP and suddle it down dfs(node, parent) would give correct price from node to end\n """\n \n g = defaultdict(set)\n \n for u, v in edges:\n g[u].add(v)\n g[v].add(u)\n \n @cache\n def dfs(node, parent):\n \n curr_price = price[node]\n m = 0 # find the max path from current node via dfs\n for v in g[node]:\n if v == parent: continue\n m = max(m, dfs(v, node))\n\n return curr_price + m # return current_price + max_price_path\n \n m = 0\n for node in range(n):\n max_price = dfs(node, -1)\n min_price = price[node]\n m = max(m, max_price - min_price)\n \n return m\n \n \n \n``` | 24 | 7 | ['Python'] | 9 |
difference-between-maximum-and-minimum-price-sum | template for tree-based dp problems with edges inputs | template-for-tree-based-dp-problems-with-0x1y | Learned this trick from @yk000123 (https://leetcode.com/problems/minimum-score-after-removals-on-a-tree/discuss/2198125/Python-O(n2)-Iterate-two-edges-with-cach | leetcode_dafu | NORMAL | 2023-01-15T04:02:30.321623+00:00 | 2023-01-15T05:27:25.134708+00:00 | 3,769 | false | Learned this trick from @yk000123 (https://leetcode.com/problems/minimum-score-after-removals-on-a-tree/discuss/2198125/Python-O(n2)-Iterate-two-edges-with-caching\uFF09\n\nFor tree-based dp problems that give you edges as inputs, below is the template\n\n1. store edges into an adjancent list\n2. define a dfs function with two key parameters (cur, prev) to control the direction we will move along an edge between cur and prev\n3. within dfs(cur,prev), the recursion is to call t(nxt,cur) for nxt in adj[cur]-{prev}\n4. we add memorization (@cache) so that each edge between cur and prev will only be visited twice: one from cur to prev, one from prev to cur\n5. we call dfs(i,-1) for i in range(n). -1 denotes no prev for i, so i is the root.\n\n adj=collections.defaultdict(set)\n for i,j in edges:\n adj[i].add(j)\n adj[j].add(i)\n \n @cache\n def dfs(cur,prev): \n return price[cur]+max([dfs(nxt,cur) for nxt in adj[cur]-{prev}]+[0])\n\n return max(dfs(i,-1)-price[i] for i in range(n)) \n\n\nUsing this template, we can solve all the following problems with minor edits.\n\nhttps://leetcode.com/discuss/interview-question/2751188/Lucid-OA-new-grad-SWE\n\nhttps://leetcode.com/discuss/interview-question/1463104/Media.net-or-OA-or-Minimum-cost-to-buy-oranges\n\nhttps://leetcode.com/discuss/interview-question/2639890/Media.Net(Directi)-OA-On-campus-Questions-%3A)\n\nhttps://leetcode.com/problems/minimum-score-after-removals-on-a-tree/\n\nhttps://leetcode.com/discuss/interview-question/2788156/OA-2022-or-Pythagorean-Triplets\n\n\n\n\n\n\n\n | 23 | 2 | ['Python'] | 12 |
difference-between-maximum-and-minimum-price-sum | DFS vs. BFS | dfs-vs-bfs-by-votrubac-e9kq | A path with maximum cost will always span leaf-to-leaf.\n\nThe cost will be the prices of all nodes in the path, minus the smaller price of two leaves.\n\n#### | votrubac | NORMAL | 2023-01-21T23:18:05.017232+00:00 | 2023-01-22T00:13:08.589102+00:00 | 1,107 | false | A path with maximum cost will always span leaf-to-leaf.\n\nThe cost will be the prices of all nodes in the path, minus the smaller price of two leaves.\n\n#### DFS\nWe can run DFS from each leaf, but it will be too slow.\n\nInstead, we can track and return two values from DFS: maximum costs with and without including a root in the path.\n\nIt was tricky for me to figure it out right away, and I initially came up with a BFS solution.\n\nIn the end, the logic turned out to be quite similar, though perhaps the BFS solution could be easier to follow for someone.\n\n**C++**\n```cpp\nlong long max_cost = 0;\narray<long long, 2> dfs(int i, int p, vector<vector<int>> &al, vector<int>& price) {\n array<long long, 2> res({price[i], 0});\n for (int j : al[i])\n if (j != p) {\n auto res_j = dfs(j, i, al, price);\n max_cost = max({ max_cost, res[0] + res_j[1], res[1] + res_j[0] });\n res[0] = max(res[0], res_j[0] + price[i]);\n res[1] = max(res[1], res_j[1] + price[i]);\n }\n return i == 0 ? array<long long, 2>({max_cost, 0}) : res;\n}\nlong long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n vector<vector<int>> al(n);\n for(auto& e : edges) {\n al[e[0]].push_back(e[1]);\n al[e[1]].push_back(e[0]);\n }\n return dfs(0, -1, al, price)[0];\n}\n```\n\n#### BFS\nWe can do BFS starting from leaves. For node `i`, we track two values:\n- `leaf[i]` - maximum cost so far to reach node `i`, including the price of starting leaf.\n- `root[i]` - same as above, but excluding the price of starting node. \n\nWhen we reach node `j` from node `i`, we can form a path with cost `leat[i] + root[j]` or `root[i] + leaf[j]`.\n\nThis way, we maximize the cost by combining the best rooted and non-rooted path.\n\nWe track the edges for each node in `cnt`. When we reach a node `i`, we decrement `cnt[i]`. \n\nOnce the count reaches `1`, then all subtrees have converged at node `i`, and we can go further.\n\n**C++**\n```cpp\nlong long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n long long res = 0;\n vector<vector<int>> al(n);\n vector<int> cnt(n), leaf(price), root(price), q;\n for (auto &e : edges) {\n al[e[0]].push_back(e[1]);\n al[e[1]].push_back(e[0]);\n }\n for (int i = 0; i < n; ++i) \n if ((cnt[i] = al[i].size()) == 1) {\n q.push_back(i);\n root[i] -= price[i];\n }\n while (!q.empty()) {\n vector<int> q1;\n for (int i : q) {\n --cnt[i];\n for (int j : al[i])\n if (cnt[j] > 0) {\n res = max({res, (long long)leaf[i] + root[j], (long long)root[i] + leaf[j]});\n leaf[j] = max(leaf[i] + price[j], leaf[j]);\n root[j] = max(root[i] + price[j], root[j]);\n if (--cnt[j] == 1)\n q1.push_back(j);\n }\n }\n swap(q, q1);\n }\n return res;\n}\n``` | 15 | 0 | ['C'] | 0 |
difference-between-maximum-and-minimum-price-sum | max path sum | one pass | 🔥 42ms, beats 100% | [Java] | max-path-sum-one-pass-42ms-beats-100-jav-ab2m | NOTE\nthis solution was originally posted by jason7708, and was top voted, not sure why it was later removed, this is the simplest and fasting solution I know, | byegates | NORMAL | 2023-01-20T00:09:49.998057+00:00 | 2023-01-25T19:58:35.382476+00:00 | 1,223 | false | # NOTE\nthis solution was originally posted by [jason7708](https://leetcode.com/jason7708/), and was top voted, not sure why it was later removed, this is the simplest and fasting solution I know, so I am posting it again.\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n[124. Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/description/)\nThis is actually a leaf to leaf path sum problem, the caveat is, you have to remove one leaf (from either end), so you have to return more values.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n), one pass after graph/tree created\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# [42ms](https://leetcode.com/problems/difference-between-maximum-and-minimum-price-sum/submissions/880271275/)\n```java\nclass Solution {\n long res = 0;\n List<Integer>[] g;\n int[] price;\n\n record returnType(int withLeaf, int withoutLeaf) {}\n public long maxOutput(int n, int[][] edges, int[] price) {\n this.price = price;\n \n // create adjacency list graph(tree)\n g = new List[n];\n for (int i = 0; i < n; i++) g[i] = new ArrayList<>();\n for (var e : edges) {\n g[e[0]].add(e[1]);\n g[e[1]].add(e[0]);\n }\n\n dfs(0, -1); // you can start from any root doesn\'t matter, as long as it exists\n return res;\n }\n\n private returnType dfs(int cur, int pre) {\n int withLeaf = price[cur], withoutLeaf = 0;\n for (int child : g[cur]) if (child != pre) {\n var childMax = dfs(child, cur);\n res = Math.max(res, withLeaf + childMax.withoutLeaf);\n res = Math.max(res, withoutLeaf + childMax.withLeaf);\n withLeaf = Math.max(withLeaf, childMax.withLeaf + price[cur]);\n withoutLeaf = Math.max(withoutLeaf, childMax.withoutLeaf + price[cur]);\n }\n\n return new returnType(withLeaf, withoutLeaf); // single leg\n }\n}\n``` | 14 | 0 | ['Java'] | 4 |
difference-between-maximum-and-minimum-price-sum | 💥💥 Beats 100% on runtime and memory [EXPLAINED] | beats-100-on-runtime-and-memory-explaine-6uqt | IntuitionI noticed that the tree structure allows us to explore paths efficiently from any chosen root node, so I focused on breaking down the problem into mana | r9n | NORMAL | 2024-12-27T12:27:21.439309+00:00 | 2024-12-27T12:27:21.439309+00:00 | 71 | false | # Intuition
I noticed that the tree structure allows us to explore paths efficiently from any chosen root node, so I focused on breaking down the problem into manageable subproblems: calculating the maximum path sum starting from each node (in_dp) and the maximum path sum going through the parent node to other branches (out_dp). This dual perspective lets us maximize the difference in price sums.
# Approach
I used DFS twice, first to calculate the in_dp (maximum price sums towards children) and then to compute out_dp (maximum price sums through the parent), and finally iterated through all nodes to find the maximum difference between these sums using vectors to store the in_dp and out_dp values efficiently.
# Complexity
- Time complexity:
O(n), because we traverse each node and edge exactly twice during the DFS.
- Space complexity:
O(n), for storing the adjacency list (graph) and the in_dp/out_dp vectors.
# Code
```rust []
impl Solution {
pub fn max_output(n: i32, edges: Vec<Vec<i32>>, price: Vec<i32>) -> i64 {
use std::collections::HashMap;
let mut graph: Vec<Vec<usize>> = vec![Vec::new(); n as usize];
for edge in edges {
graph[edge[0] as usize].push(edge[1] as usize);
graph[edge[1] as usize].push(edge[0] as usize);
}
let mut prices: Vec<i64> = price.into_iter().map(|p| p as i64).collect();
let mut in_dp: Vec<i64> = vec![0; n as usize];
let mut out_dp: Vec<i64> = vec![0; n as usize];
fn dfs_in(u: usize, parent: Option<usize>, graph: &Vec<Vec<usize>>, prices: &Vec<i64>, in_dp: &mut Vec<i64>) {
for &v in &graph[u] {
if Some(v) != parent {
dfs_in(v, Some(u), graph, prices, in_dp);
in_dp[u] = in_dp[u].max(in_dp[v]);
}
}
in_dp[u] += prices[u];
}
fn dfs_out(
u: usize,
parent: Option<usize>,
graph: &Vec<Vec<usize>>,
prices: &Vec<i64>,
in_dp: &Vec<i64>,
out_dp: &mut Vec<i64>,
) {
let mut max1 = -1;
let mut max2 = -1;
for &v in &graph[u] {
if Some(v) != parent {
if in_dp[v] >= max1 {
max2 = max1;
max1 = in_dp[v];
} else if in_dp[v] > max2 {
max2 = in_dp[v];
}
}
}
for &v in &graph[u] {
if Some(v) != parent {
let mut longest = if in_dp[v] == max1 { max2 } else { max1 };
out_dp[v] = (out_dp[u].max(longest) + prices[u]).max(0);
dfs_out(v, Some(u), graph, prices, in_dp, out_dp);
}
}
}
dfs_in(0, None, &graph, &prices, &mut in_dp);
dfs_out(0, None, &graph, &prices, &in_dp, &mut out_dp);
let mut result = 0;
for root in 0..n as usize {
result = result.max((in_dp[root].max(out_dp[root] + prices[root]) - prices[root]).max(0));
}
result
}
}
``` | 12 | 0 | ['Array', 'Dynamic Programming', 'Tree', 'Depth-First Search', 'Graph', 'Rust'] | 0 |
difference-between-maximum-and-minimum-price-sum | Java using DFS, Weighted Directed Tree with Comments | java-using-dfs-weighted-directed-tree-wi-v36a | # Intuition \n\n\n# Approach\nThe naive approach asks us to dfs the tree from node u, for every node in the tree.\nThis results in a time complexity of O(n^2) | shiva1718 | NORMAL | 2023-01-15T04:42:21.449239+00:00 | 2023-01-16T14:45:16.439870+00:00 | 2,089 | false | <!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe naive approach asks us to dfs the tree from node u, for every node in the tree.\nThis results in a time complexity of O(n^2).\n\nIn order to reduce the time complexity to O(n), we need to try to update maximum paths information for every node in the tree while we are doing dfs for a particular node.\n\nThis can be achived by using a weighed directed tree. Here every weight from node u to node v gives us the length of the longest path starting from node u using the edge u-v.\nTherefore, a directed weight from node u to v can be used to store results in order to avoid extra computations. This information can be used to calculate maximum path sum for other nodes, without having to do dfs again.\n\nThis means, the longest path for any node u, is the maximum value out of all the edges going out from node u.\n\nNote: the minimum path from any node u, is the node u itself as the given tree can\'t contain nodes with negative values according to constraints.\n\nSo now that we have the minimum and maximum path from any given node of the tree(computed). In order to find the path with maximum difference, we just iterate over all the nodes and compute the maximum value and return it as the result\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n^2)$$ (worst case, it happens for a star graph)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(2 * n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public long maxOutput(int n, int[][] edges, int[] price) {\n Map<Integer, Long>[] adjList = new Map[n];\n for (int i = 0; i < n; i++) {\n adjList[i] = new HashMap<>();\n }\n for (int[] edge : edges) {\n adjList[edge[0]].put(edge[1], 0L);\n adjList[edge[1]].put(edge[0], 0L);\n }\n // Above we simply construct the adjacency list for the given tree.\n long res = 0;\n // Below, we dfs every node of our tree,\n // but every iteration won\'t be O(n),\n // because we use information from previous dfs iteration\n // to compute edge values.\n for (int i = 0; i < n; i++) {\n res = Math.max(res, dfs(adjList, price, i, -1) - price[i]);\n }\n return res;\n }\n \n private long dfs(Map<Integer, Long>[] tree, int[] price, int cur, int parent) {\n long maxPath = 0;\n for (int child : tree[cur].keySet()) {\n if (child != parent) {\n // get the weight of edge from node cur to node child.\n long temp = tree[cur].get(child);\n\n // if the weight of the edge is not already computed,\n // then we compute by calling dfs for this\n // adjacent or child node.\n if (temp == 0) {\n temp = dfs(tree, price, child, cur);\n tree[cur].put(child, temp);\n }\n // maxPath starting from node cur is updated.\n maxPath = Math.max(maxPath, temp);\n }\n }\n // cost of including current path in previous\n // stack call is returned.\n return maxPath + price[cur];\n }\n}\n``` | 12 | 2 | ['Tree', 'Depth-First Search', 'Java'] | 6 |
difference-between-maximum-and-minimum-price-sum | [C++] Farthest node from each node (+ Additional Practice Problems) | c-farthest-node-from-each-node-additiona-a8io | Difference Between Maximum and Minimum Price Sum\n\nThis is a standard tree problem where it is required find the farthest node from every node. At first glance | Aryan-V-S | NORMAL | 2023-01-15T04:35:33.124650+00:00 | 2023-01-15T18:06:45.007623+00:00 | 2,104 | false | # Difference Between Maximum and Minimum Price Sum\n\nThis is a standard tree problem where it is required find the farthest node from every node. At first glance, the problem seems difficult but with a few observations, it can be made simple. You can practice similar problems on CSES (check out [this](https://cses.fi/problemset/task/1131), [this](https://cses.fi/problemset/task/1132/) and [this](https://cses.fi/problemset/task/1133)). There are many that are similar in nature on Leetcode too.\n\n- For each node, we must find the distance to the farthest node.\n- Start by finding the diameter of the tree. The diameter of a tree is the longest path between two leaf nodes. This can be done by starting a DFS/BFS at _any_ node and selecting the farthest node as a diameter endpoint. Let this node be `U`.\n- Perform a DFS/BFS starting at node `U` and find the farthest node. This is the other diameter endpoint. Let this node be `V`.\n- The farthest node from each node is the maximum distance from either of the diametric endpoints `U` or `V`. That is:\n\n```\nmax_distance[i] = max(distance_from_diametric_endpoint_U[i], distance_from_diametric_endpoint_V[i])\n```\n\n- We have to account for one more detail in this problem, and that is the minimum path sum which must be subtracted. This is simply a single node value (because more nodes have higher path sum). It must be a path endpoint (because you can\'t remove a node in the middle of a path as it will no longer be a path) and there are two choices for each path (start and end nodes). Iterate over all nodes and find the maximum value by considering both path endpoints.\n\nTime Complexity: **O(n)**\n\nSpace Complexity: **O(n)**\n\n```cpp\nclass Solution {\n public:\n long long maxOutput (int n, vector <vector <int>>& edges, vector <int>& price) {\n std::vector <std::vector <int>> graph (n);\n \n for (auto &e: edges) {\n graph[e[0]].push_back(e[1]);\n graph[e[1]].push_back(e[0]);\n }\n \n auto dfs = [&] (auto self, int u, std::vector <int64_t> &depth) -> void {\n for (int v: graph[u]) {\n if (depth[v] == -1) {\n depth[v] = depth[u] + price[v];\n self(self, v, depth);\n }\n }\n };\n \n std::vector <int64_t> depth_x (n, -1);\n depth_x[0] = price[0];\n dfs(dfs, 0, depth_x);\n \n auto u = std::max_element(depth_x.begin(), depth_x.end()) - depth_x.begin();\n \n std::vector <int64_t> depth_y (n, -1);\n depth_y[u] = price[u];\n dfs(dfs, u, depth_y);\n \n auto v = std::max_element(depth_y.begin(), depth_y.end()) - depth_y.begin();\n \n depth_x = std::vector <int64_t> (n, -1);\n depth_x[v] = price[v];\n dfs(dfs, v, depth_x);\n \n int64_t ans = 0;\n \n for (int i = 0; i < n; ++i) {\n ans = std::max(ans, depth_x[i] - price[i]);\n ans = std::max(ans, depth_y[i] - price[i]);\n }\n \n return ans;\n }\n};\n```\n | 10 | 0 | ['Tree', 'Depth-First Search', 'Breadth-First Search', 'C++'] | 5 |
difference-between-maximum-and-minimum-price-sum | C++ understandable code using rerooting | c-understandable-code-using-rerooting-by-mgpa | \n\n\n// firstly i am precomputing the maximum path sum for each node (called sub) using dfs function assuming tree rooted at node 0.\n// Now we are olny left w | avinash1904 | NORMAL | 2023-01-15T06:53:20.523528+00:00 | 2023-01-17T21:00:19.496875+00:00 | 1,478 | false | ```\n\n\n// firstly i am precomputing the maximum path sum for each node (called sub) using dfs function assuming tree rooted at node 0.\n// Now we are olny left with rerooting at all the nodes and get the maximum of all. I am storing it in dp \n\n//explanation of rerooting function\nconsider the tree\n 0\n\t\t / \\\n 1 2\n\t/ \\ / \\\n 3 4 5 6\n prices:= 1,2,3,4,5,6,7\n \n suppose we are at 0th node then we have to reroot at all the child of node 0 i.e.(1,2)\n now suppose i go for node 2 then what i am doing that assume 2 is not a child of node 0 and calculate the maximum path sum for node 0.\n \n long long mx=0;\n for(auto it:g[v]){\n if(it==to)continue;\n mx=max(mx,sub[it]);\n }\nnow it is quite simple that dp[2]=max(sub[2]-price[2],mx+price[2]);\n dp[to]=max(sub[to]-price[to],mx+price[v]);\n \n //one thing to note that when we go gor node 2 the path sum value of node 0 (sub[0]) will change for that subtree that\'s why i am doing\n sub[v]=mx+price[v];\n\t\n\tand after coming out of reroot call \n\tsetting it to the initial value(long long tmp=sub[v])\n sub[v]=tmp;\n\t \n\n\nCODE:-\n\n vector<long long>sub; \nbool comp(int &i,int &j){\n return (sub[i]>sub[j]);\n }\nclass Solution {\npublic:\n \n \n long long solve(int v,int p,vector<int>g[],vector<int>&price){\n sub[v]=price[v];\n long long mx=0;\n for(auto to:g[v]){\n if(to==p)continue;\n mx=max(mx,solve(to,v,g,price));\n }\n sub[v]+=mx;\n return sub[v];\n }\n void reroot(int v,int p,vector<int>g[],vector<int>&price,long long &ans,vector<long long>&dp){\n long long tmp=sub[v];\n \n for(auto to:g[v]){\n if(to==p)continue;\n \n long long mx=0;\n int j=0;//to ensure we are checking just two childs\n for(auto it:g[v]){\n if(it==to){\n continue;\n j++;}\n mx=max(mx,sub[it]);\n j++;\n if(j>2)break;\n }\n sub[v]=mx+price[v];\n dp[to]=max(sub[to]-price[to],mx+price[v]);\n reroot(to,v,g,price,ans,dp);\n sub[v]=tmp;\n }\n \n }\n \n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n vector<int>g[n];\n \n for(auto it:edges){\n g[it[0]].push_back(it[1]);\n g[it[1]].push_back(it[0]);\n }\n sub=vector<long long>(n);\n vector<long long>dp(n);// dpi denotes the answer if i is root\n solve(0,-1,g,price);\n \n for(int i=0;i<n;i++){\n sort(g[i].begin(),g[i].end(),comp);\n }\n \n long long ans=0;\n dp[0]=sub[0]-price[0];\n reroot(0,-1,g,price,ans,dp);\n \n for(int i=0;i<n;i++)ans=max(ans,dp[i]);\n \n return ans;\n }\n};\n``` | 9 | 1 | ['Tree', 'Depth-First Search', 'C'] | 5 |
difference-between-maximum-and-minimum-price-sum | Python 3 || 16 lines , dfs || T/S: 81 % / 55% | python-3-16-lines-dfs-ts-81-55-by-spauld-3gxt | Here\'s the intuition:\n\n- We assign a three-uplestateto each node. the root and each leaf gets (0,price,0), and each other link\'sstate is determined by the r | Spaulding_ | NORMAL | 2023-01-17T07:24:31.226895+00:00 | 2024-06-23T00:46:03.959121+00:00 | 674 | false | Here\'s the intuition:\n\n- We assign a three-uple`state`to each node. the root and each leaf gets `(0,price,0)`, and each other link\'s`state` is determined by the recurence relation in`dfs`. The figure below is for Example 1 in the problem\'s description.\n\n- Best way to figure it out is to trace it from the recurence relation. The correct answer is`24`, which is `state[0]` for `node 1`. BTW, if you start from a root other than`0`, the `state` for some nodes may change, but the answer doesn\'t.\n\n\n\n______\n\nHere\'s the code\n```\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], \n price: List[int]) -> int:\n\n g = defaultdict(list)\n for a, b in edges:\n g[a].append(b)\n g[b].append(a)\n\n def dfs(node1, node2 =-1):\n p = price[node1]\n state = (0, p, 0)\n\n for n in g[node1]:\n if n == node2: continue\n\n (a1, a2, a3), (b1, b2, b3) = state, dfs(n, node1)\n \n state = (max(a1, b1, a2 + b3, a3 + b2),\n max(a2, b2 + p),\n max(a3, b3 + p))\n\n return state\n\n\n if n <= 2: return sum(price) - min(price)\n\n for node in range(n):\n if len(g[node]) > 1:\n return dfs(node)[0]\n\n```\n[https://leetcode.com/problems/difference-between-maximum-and-minimum-price-sum/submissions/1297179636/](https://leetcode.com/problems/difference-between-maximum-and-minimum-price-sum/submissions/1297179636/)\n```\n\nI think that time complexity is *O*(*N*) and space complexity is *O*(*N*), | 8 | 2 | ['Python3'] | 2 |
difference-between-maximum-and-minimum-price-sum | Greatest Path Sum Problem - a Variation | greatest-path-sum-problem-a-variation-by-8dqt | Observation\nprice is positive integer, so:\n1. max price sum path should be as long as possible => the path must go to a leaf, and the new root itself must als | antarestrue | NORMAL | 2023-01-15T06:13:10.048816+00:00 | 2023-01-16T07:22:47.704545+00:00 | 722 | false | **Observation**\n`price` is positive integer, so:\n1. max price sum path should be as long as possible => the path must go to a leaf, and the new root itself must also be qualified as a leaf\n2. min price sum path must be only the new root, which is one end of the path\n\nFor (1), there is a boilerplate:\n```\nm = 0\ndef rec(p):\n\tnonlocal m\n\ta = rec(p.left)\n\tb = rec(p.right)\n\tm = max(m, a + b + p.val)\n\treturn max(a, b) + p.val\nrec(0)\nreturn m\n```\nWe start from node `0` as the old root, get the values from sub-trees and try to combine them. And then, instead of returning the combined value, we still return the max value while record the max of combined value all the way.\n\nNow, let\'s take (2.) into account. For each sub-tree, we need to return two values - \n`a`. the max price sum, which means "if the new root is not here"\n`b`. the max price sum minus a leaf price, which means "if the new root is here".\n\nWhen combining the values, we use `a + b + price[p]`, where `a` is from a sub-tree and `b` is from another sub-tree. The path must go from one sub-tree to another sub-tree if there are two or more sub-trees. It will not stop at anywhere because of Observation (1.).\n\n\n\nWhat if a node has only one sub-tree? In this case, the new root can be the current node `p`. This is equivalent to have two sub-trees, one real, one fake, and let the fake sub-tree to have `b = -price[p]`.\n\nWritten in code, it would be like:\n```\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n g = [[] for _ in range(n)]\n for a, b in edges:\n g[a].append(b)\n g[b].append(a)\n \n m = 0\n def rec(p, pp):\n nonlocal m\n if len(g[p]) == 0:\n return (0, 0)\n\t\t\t# early return; not really necessary\n if len(g[p]) == 1 and pp == g[p][0]:\n return (price[p], 0)\n ma = 0\n mb = -price[p]\n for q in g[p]:\n if q == pp: continue\n a, b = rec(q, p)\n m = max(m, ma + b + price[p], mb + a + price[p])\n ma = max(ma, a)\n mb = max(mb, b)\n return (ma + price[p], mb + price[p])\n \n rec(0, 0)\n return m\n``` | 8 | 0 | ['Python'] | 2 |
difference-between-maximum-and-minimum-price-sum | C++ DFS + Memo | c-dfs-memo-by-szlin13-ejq4 | $O(n^2)$ Easy Solution (AC during contest)\n\nclass Solution {\npublic:\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n | szlin13 | NORMAL | 2023-01-15T04:34:03.774328+00:00 | 2023-01-21T08:10:44.505626+00:00 | 1,484 | false | 1. $O(n^2)$ Easy Solution (AC during contest)\n```\nclass Solution {\npublic:\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n using ll = long long;\n vector<vector<int>> adj(n);\n for (auto& e: edges) {\n adj[e[0]].push_back(e[1]);\n adj[e[1]].push_back(e[0]);\n }\n vector<unordered_map<int, ll>> dp(n);\n ll ans = 0;\n function<ll(int, int)> dfs = [&] (int u, int p) {\n if (dp[u].count(p))\n return dp[u][p];\n ll ret = 0;\n for (int v: adj[u]) {\n if (v != p)\n ret = max(ret, dfs(v, u));\n }\n return dp[u][p] = ret + price[u];\n };\n for (int i = 0; i < n; i++) {\n if (size(adj[i]) == 1)\n ans = max(ans, dfs(i, -1) - price[i]);\n }\n return ans;\n }\n};\n```\n2. $O(n)$ Solution from [@jason7708](https://leetcode.com/problems/difference-between-maximum-and-minimum-price-sum/solutions/3052985/c-dfs-beats-100/)\n```\nclass Solution {\npublic:\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n using ll = long long;\n vector<vector<int>> adj(n);\n for (auto& e: edges) {\n adj[e[0]].push_back(e[1]);\n adj[e[1]].push_back(e[0]);\n }\n ll ans = 0;\n function<pair<ll, ll>(int, int)> dfs = [&] (int u, int p) {\n pair<ll, ll> ret = {price[u], 0};\n for (int v: adj[u]) {\n if (v != p) {\n auto [a, b] = dfs(v, u);\n ans = max(ans, max(ret.first + b, ret.second + a));\n ret.first = max(ret.first, a + price[u]);\n ret.second = max(ret.second, b + price[u]);\n }\n }\n return ret;\n };\n dfs(0, -1);\n return ans;\n }\n};\n``` | 6 | 0 | ['C++'] | 3 |
difference-between-maximum-and-minimum-price-sum | Java , simple DFS + MEMO | java-simple-dfs-memo-by-gavinzhan-0rlb | Java\nclass Solution {\n\tprivate long max;\n\tprivate ArrayList<Integer>[] tree;\n\tprivate int[] price;\n\tprivate long res;\n\tprivate boolean[] visited;\n\n | gavinzhan | NORMAL | 2023-01-15T04:03:21.790047+00:00 | 2023-01-27T01:21:58.341991+00:00 | 1,713 | false | ```Java\nclass Solution {\n\tprivate long max;\n\tprivate ArrayList<Integer>[] tree;\n\tprivate int[] price;\n\tprivate long res;\n\tprivate boolean[] visited;\n\n\n\tpublic long maxOutput(int n, int[][] edges, int[] price) {\n\t\tif (n == 1) return 0;\n\n\t\tthis.price = price;\n\t\ttree = new ArrayList[n];\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\ttree[i] = new ArrayList<>();\n\t\t}\n\t\tfor (int[] e : edges) {\n\t\t\ttree[e[0]].add(e[1]);\n\t\t\ttree[e[1]].add(e[0]);\n\t\t}\n\n\t\tvisited = new boolean[n];\n\t\tvisited[0] = true;\n\t\tdfs(0);\n\n\t\treturn res;\n\t}\n\n\t// return long[]{longest path with leaf, longest path without leaf}\n\tprivate long[] dfs(int node) {\n\t\tif (tree[node].size() == 1 && node != 0) {\n\t\t\treturn new long[]{price[node], 0};\n\t\t}\n\t\tlong temp = res;\n\t\tint i0 = -1, i1 = -1; // child id of the longest path and path without leaf\n\t\tlong l0 = 0, l1 = 0; // the longest path with leaf and path without leaf\n\t\tlong s0 = 0, s1 = 0; // the 2nd longest\n\n\t\tfor (int child : tree[node]) {\n\t\t\tif (visited[child]) continue;\n\t\t\tvisited[child] = true;\n\t\t\tlong[] sub = dfs(child);\n\n\t\t\tif (sub[0] >= l0) {\n\t\t\t\ts0 = l0;\n\t\t\t\tl0 = sub[0];\n\t\t\t\ti0 = child;\n\t\t\t} else if (sub[0] > s0) {\n\t\t\t\ts0 = sub[0];\n\t\t\t}\n\n\t\t\tif (sub[1] >= l1) {\n\t\t\t\ts1 = l1;\n\t\t\t\tl1 = sub[1];\n\t\t\t\ti1 = child;\n\t\t\t} else if (sub[1] > s1) {\n\t\t\t\ts1 = sub[1];\n\t\t\t}\n\t\t}\n\n\t\tif (s0 == 0) {\n\t\t\t// only one child. case: example 2\n\t\t\tres = Math.max(res, Math.max(l0, l1 + price[node]));\n\t\t} else {\n\t\t\tlong path = i0 != i1 ? price[node] + l0 + l1 \n\t\t\t\t: price[node] + Math.max(l0 + s1, s0 + l1);\n\t\t\tres = Math.max(res, path);\n\t\t}\n\n\t\treturn new long[]{l0 + price[node], l1 + price[node]};\n\t}\n}\n/*\n// this version is TLE after new test cases being added.\nclass Solution {\n private long max;\n private ArrayList<Integer>[] tree;\n private int[] price;\n private HashMap<Long, Long> memo;\n \n public long maxOutput(int n, int[][] edges, int[] price) {\n this.price = price;\n memo = new HashMap<>();\n tree = new ArrayList[n];\n for (int i = 0; i < n; i++) {\n tree[i] = new ArrayList<>();\n }\n for (int[] e : edges) {\n tree[e[0]].add(e[1]);\n tree[e[1]].add(e[0]);\n }\n \n long res = 0;\n for (int i = 0; i < n; i++) {\n if (tree[i].size() == 1) {\n long temp = dfs(-1, i);\n res = Math.max(res, temp - price[i]);\n }\n }\n return res;\n }\n \n\t// return the length of the longest path on the subTree\n private long dfs(int parent, int node) {\n long key = (long)(parent + 1) * 1_000_000 + node;\n if (memo.containsKey(key)) return memo.get(key);\n \n long res = price[node];\n for (int child : tree[node]) {\n if (child != parent) {\n res = Math.max(res, price[node] + dfs(node, child));\n }\n }\n \n memo.put(key, res);\n return res;\n }\n}\n*/\n``` | 6 | 1 | [] | 1 |
difference-between-maximum-and-minimum-price-sum | [Python3] DP Tree Re-Rooting - Simple Solution | python3-dp-tree-re-rooting-simple-soluti-zqhc | Intuition\n Describe your first thoughts on how to solve this problem. \n- Problem with tree and asked to find total number satisfy something or find min, max - | dolong2110 | NORMAL | 2024-08-23T07:54:19.330006+00:00 | 2024-08-23T07:54:19.330035+00:00 | 116 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Problem with tree and asked to find total number satisfy something or find min, max -> DP tree\n- The problem ask to find something between all the root -> we need re-root.\n- You can find more about DP Tree Re-Rooting [here](https://usaco.guide/gold/all-roots?lang=java).\n- We can see that the minimum path always contains only the root. Thus the max_path - min_path = max_substree_path + root_value - root_value = max_subtree_path.\n- Thus We only need to find the maximum path for subtree of the root.\n- Finally, the problems ask us to find the maximum of the max subtree path of each root.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- First, we choose any node as the root. Traverse to all children node and find the max subtree path for each node.\n- The the chosen root node, it is the max subtree path of its. However for all the children node, it only has the max_path of children subtree. But if we consider the current child node as root we did not consider its maximum of parent subtree yet.\n- `max_subtree_current_node = max(max_subtree_parent + price[parent], max_subtree_children)` with `max_subtree_children` alreday known by previous calculating by `dfs1()`\n- The `max_parent_subtree` can pass through current node, in this case we choose the second highest `parent_subtree`. To do this for each node, we keep update two values: first and second highest of the max subtree path.\n- \n\n# Complexity\n- Time complexity: $$O(N)$$\n\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(N)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n res = 0\n dp = [[0, 0] for _ in range(n)]\n graph = collections.defaultdict(list)\n for u, v in edges:\n graph[u].append(v)\n graph[v].append(u)\n\n def dfs1(node: int = 0, parent: int = -1) -> int:\n for next_node in graph[node]:\n if next_node == parent: continue\n v = dfs1(next_node, node) + price[next_node]\n if v >= dp[node][0]: dp[node][0], dp[node][1] = v, dp[node][0]\n elif v > dp[node][1]: dp[node][1] = v\n\n return dp[node][0]\n\n def dfs2(node: int = 0, parent: int = -1) -> None:\n if parent != - 1:\n if dp[node][0] + price[node] == dp[parent][0]: parent_subtree_max_value = dp[parent][1] + price[parent]\n else: parent_subtree_max_value = dp[parent][0] + price[parent]\n if parent_subtree_max_value >= dp[node][0]: dp[node][0], dp[node][1] = parent_subtree_max_value, dp[node][0]\n elif parent_subtree_max_value > dp[node][1]: dp[node][1] = parent_subtree_max_value\n\n for next_node in graph[node]:\n if next_node == parent: continue\n dfs2(next_node, node)\n\n dfs1()\n dfs2()\n\n return max(x[0] for x in dp)\n``` | 5 | 0 | ['Array', 'Dynamic Programming', 'Tree', 'Graph', 'Python3'] | 0 |
difference-between-maximum-and-minimum-price-sum | ✅ 🔥 O(n) Python3 || ⚡ solution | on-python3-solution-by-maary-mict | \nfrom typing import List\nfrom collections import defaultdict\n\n\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) - | maary_ | NORMAL | 2023-03-13T17:03:08.597295+00:00 | 2023-03-13T17:03:27.160052+00:00 | 101 | false | ```\nfrom typing import List\nfrom collections import defaultdict\n\n\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n graph = defaultdict(list)\n for a, b in edges:\n graph[a].append(b)\n graph[b].append(a)\n\n def dfs(node, parent=-1):\n current_price = price[node]\n max_output = (0, current_price, 0)\n\n for neighbor in graph[node]:\n if neighbor == parent:\n continue\n\n neighbor_output = dfs(neighbor, node)\n combined_output = (\n max(\n max_output[0],\n neighbor_output[0],\n max_output[1] + neighbor_output[2],\n max_output[2] + neighbor_output[1],\n ),\n max(max_output[1], neighbor_output[1] + current_price),\n max(max_output[2], neighbor_output[2] + current_price),\n )\n\n max_output = combined_output\n\n return max_output\n\n if n <= 2:\n return sum(price) - min(price)\n\n for node in range(n):\n if len(graph[node]) > 1:\n return dfs(node)[0]\n\n``` | 5 | 1 | ['Python', 'Python3'] | 0 |
difference-between-maximum-and-minimum-price-sum | JAVA | DFS + Memoization | Approach, Complexities - explained ✅ | java-dfs-memoization-approach-complexiti-vc9t | Please Upvote :D\n---\nThis solution is inspired from shiva1718**\njava []\nclass Solution {\n // globally declaring data structure to store the adjacency\n | sourin_bruh | NORMAL | 2023-01-15T15:18:37.801846+00:00 | 2023-01-15T18:23:23.604487+00:00 | 640 | false | # Please Upvote :D\n---\n*This solution is inspired from **[shiva1718](https://leetcode.com/problems/difference-between-maximum-and-minimum-price-sum/solutions/3052821/java-using-dfs-weighted-directed-tree-with-comments/?orderBy=most_votes\n)***\n``` java []\nclass Solution {\n // globally declaring data structure to store the adjacency\n private Map<Integer, Long>[] adj;\n public long maxOutput(int n, int[][] edges, int[] price) {\n adj = new Map[n]; // initialising the adjacency map array\n for (int i = 0; i < n; i++) {\n adj[i] = new HashMap<>();\n }\n // populating the adjacency map array\n for (int[] e : edges) {\n adj[e[0]].put(e[1], 0L);\n adj[e[1]].put(e[0], 0L);\n }\n\n long maxDiff = 0; // to store the maximum difference\n // for each node from 0 -> n-1, check the maximum achievable difference\n for (int i = 0; i < n; i++) {\n long currDiff = dfs(i, -1, price) - price[i]; // difference between path sum and node price\n // our dfs will give us the maximum achievable sum of all possible paths as i (node) as our endpoint\n maxDiff = Math.max(maxDiff, currDiff);\n }\n\n return maxDiff; // return maximum difference\n }\n\n private long dfs(int currNode, int parent, int[] price) {\n long maxPathSum = 0; // to store the maximum path sum achieved at current node\n // check for child nodes connected to our current node (child are stores a key in the map)\n for (int child : adj[currNode].keySet()) {\n if (child == parent) { // we don\'t want to go back to our parent\n continue; // so continue if condition is hit\n }\n // now we will check what is the maximum sum that has already been achieved at our child\n // map stores the node as key, and the maximum sum that is achievable at that node as an endpoint from every direction/path\n long maxSumFromChild = adj[currNode].get(child);\n if (maxSumFromChild == 0) { // if that maximum child path sum was not already computed\n maxSumFromChild = dfs(child, currNode, price); // we will computed it by calling dfs at that child node\n adj[currNode].put(child, maxSumFromChild); // and we will put that maximum child sum by mapping it to the child node value\n }\n\n // Now we will update the maxPathSum (of our current node) with the max sum from our current child\n // this updation will be done after fetching max child path sum for each child \n maxPathSum = Math.max(maxPathSum, maxSumFromChild); \n }\n \n // finally we have the maximum acheivable child path sum from every child of our current node\n // so what is the max path sum for our current node? \n // it is the sum of the max child sum and price of our current node (which will be given by price[] array)\n return maxPathSum + price[currNode]; // return the maximum sum achieved from all directions as currentNode as our end point\n // it will also be utilised upon occasional backtracking (if child path sum is not already computed, dfs will be called otherwise not)\n }\n}\n```\n---\n### Time Complexity:\nAt worst case it\'d be $$O(n ^ 2)$$ but it is much better than that in general because we are not calling dfs for our node everytime. The call would be occasional, only when the sum of our node is not already computed we will call dfs. And as we will compute the node path sums, the requirement to call dfs for uncomputed node sums will decrease by a lot because we will have them already computed before. So the complexity kind of gets amotized to $$O(n)$$.\n\n---\n### Space complexity: \n$$O(n ^ 2)$$, because we are storing all the connected nodes attached to all the nodes of our graph.\n | 3 | 0 | ['Depth-First Search', 'Java'] | 1 |
difference-between-maximum-and-minimum-price-sum | Very simple DFS + DP Explained | very-simple-dfs-dp-explained-by-srilekha-22j1 | Intuition\n Describe your first thoughts on how to solve this problem. \nAssuming any of the nodes can be root, we will check for each node.\nFor any node:\n | srilekhapaul | NORMAL | 2023-01-15T05:47:24.237246+00:00 | 2023-03-02T16:51:19.479086+00:00 | 828 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAssuming any of the nodes can be root, we will check for each node.\nFor any node:\n Mininum sum= node.val (as -ve numbers are not present)\n Maximum sum= node.val + max of all the paths through children ie. Maximum Sum (child) \n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nThe tree can be though of as an undirected graph, with no cycle (only 2-way parent child relationship). We can create an adjacency list using the edges.\n\nWe can calculate the maximum sum recursively through DFS.\nBut as this DFS will be called for each nodes, so the time comlexity will increase to O(n)*TC(DFS)=O(n)*O(n)\n\nTo reduce this, we can use caching or DP Memoization as there will be repeated subproblems. This will bring down the time complexity to O(n)\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n #DP+DFS\n adj_list=collections.defaultdict(list)\n for x,y in edges:\n adj_list[x].append(y)\n adj_list[y].append(x)\n \n dp={}\n def dfs(node,par)->int:\n if (node,par) in dp:\n return dp[(node,par)]\n \n sumC=0\n for child in adj_list[node]:\n if child!=par:\n sumC=max(sumC,dfs(child,node))\n dp[(node,par)]=sumC+price[node]\n return dp[(node,par)]\n \n cost=0 \n for key in adj_list:\n maxV=dfs(key,-1)\n minV=price[key]\n cost=max(cost,maxV-minV)\n return cost\n \n```\n\nPlease UPVOTE if this post helps.\n | 3 | 0 | ['Dynamic Programming', 'Depth-First Search', 'Memoization', 'Python', 'Python3'] | 2 |
difference-between-maximum-and-minimum-price-sum | C++ || IN - OUT TREE DP || O(n) | c-in-out-tree-dp-on-by-anmol_singh098-hzll | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Anmol_Singh098 | NORMAL | 2023-09-02T08:02:18.120022+00:00 | 2023-09-02T08:02:18.120047+00:00 | 371 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(Adjacency List Size + 3*N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n#define pi pair<long long,long long>\n#define F first\n#define S second\n\nclass Solution {\npublic:\n vector<long long> indp,outdp;\n vector<vector<int>> adj;\n vector<pi> maxVal;\n\n void dfs1(int node,int par,vector<int> &price){\n indp[node]=0;\n long long mx =0;\n priority_queue<int,vector<int>,greater<int>> pq;\n for(auto ch : adj[node]){\n if(ch==par) continue;\n dfs1(ch,node,price);\n mx = max(mx,indp[ch]);\n pq.push(indp[ch]);\n if(pq.size()>2) pq.pop();\n }\n // To calculate 1st max ans 2nd max\n if(pq.size()==0){\n maxVal[node]= {-1e9,-1e9};\n }\n else if(pq.size()==1){\n long long max1 = pq.top();\n maxVal[node]={max1,-1e9};\n }\n else{\n long long max2 = pq.top();\n pq.pop();\n long long max1 = pq.top();\n maxVal[node] = {max1,max2};\n }\n\n ////\n indp[node]+=(mx+price[node]);\n }\n\n void dfs2(int node,int par,vector<int> &price){\n \n if(par==-1) outdp[node] = price[node];\n else{\n int nodeMx = indp[node];\n pi mxv= maxVal[par];\n if(outdp[par]> indp[par]) outdp[node] = (outdp[par] + price[node]);\n else{\n if(mxv.F>indp[node]) outdp[node] = (indp[par]+price[node]);\n else{\n if(mxv.F == mxv.S) outdp[node]=(mxv.S+price[node]+price[par]);\n else{\n if(mxv.S == -1) outdp[node] = outdp[par] + price[node];\n else outdp[node]= max(outdp[par],(mxv.S+price[par]))+price[node];\n }\n }\n }\n }\n for(auto ch : adj[node]){\n if(ch==par) continue;\n dfs2(ch,node,price);\n }\n }\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n indp.resize(n);\n outdp.resize(n);\n maxVal.resize(n);\n adj.resize(n);\n for(auto e : edges){\n adj[e[0]].push_back(e[1]);\n adj[e[1]].push_back(e[0]);\n }\n\n dfs1(0,-1,price);\n dfs2(0,-1,price);\n long long ans = 0;\n for(int i =0;i<n;i++){\n ans = max(ans,max(indp[i],outdp[i])-price[i]);\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['Dynamic Programming', 'Tree', 'C++'] | 0 |
difference-between-maximum-and-minimum-price-sum | c++ || simple || DFS calls | c-simple-dfs-calls-by-12345556-sw7r | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | 12345556 | NORMAL | 2023-08-13T09:46:51.669537+00:00 | 2023-08-13T09:46:51.669578+00:00 | 187 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n #define ll long long int\n #define pii pair<ll,ll>\n #define ff first\n #define ss second\n long long dfs(int s,int par,vector<vector<int>>& g,vector<int> &p,vector<pii> &val,vector<int> &vv)\n {\n p[s]=par;\n vector<long long> a;\n for(auto i:g[s])\n {\n if(i!=par)\n {\n long long t;\n t=dfs(i,s,g,p,val,vv);\n a.push_back(t);\n }\n }\n sort(a.begin(),a.end(),greater<long long> ());\n long long x=0,y=0;\n if(a.size()>0)\n {\n x=a[0];\n }\n if(a.size()>1)\n {\n y=a[1];\n }\n val[s]={x,y};\n return x+=vv[s];\n }\n void dfs1(int s,int par,vector<vector<int>>& g,vector<int> &p,vector<pii> &val,vector<int> &vv,ll &ans)\n {\n \n ans=max(val[s].ff,ans);\n if(par!=-1)\n {\n ll vm=vv[par];\n if(val[par].ff==val[s].ff+vv[s])\n {\n vm+=val[par].ss;\n }\n else{\n vm+=val[par].ff;\n }\n if(val[s].ff<vm)\n {\n ll tt=val[s].ff;\n val[s].ff=vm;\n val[s].ss=tt;\n }\n else if(val[s].ss<vm)\n {\n val[s].ss=vm;\n }\n ans=max(ans,vm);\n }\n // cout<<ans<<" "<<s<<endl;\n for(auto i:g[s])\n {\n if(i!=par)\n {\n dfs1(i,s,g,p,val,vv,ans);\n }\n }\n\n\n\n }\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n vector<int> p(n,-1);\n vector<pii> val(n);\n vector<vector<int>> g(n);\n for(auto& i:edges)\n {\n int u=i[0];\n int v=i[1];\n g[u].push_back(v);\n g[v].push_back(u);\n }\n int z=dfs(0,-1,g,p,val,price);\n ll ans=0;\n dfs1(0,-1,g,p,val,price,ans);\n for(auto i:val)\n {\n // cout<<i.ff<<" "<<i.ss<<endl;\n }\n return ans;\n }\n};\n``` | 2 | 1 | ['C++'] | 0 |
difference-between-maximum-and-minimum-price-sum | ✅ Easy | ✨ O(N) | 🏆 Most Efficient Solution | 👍 Simple Code with Explanations. | easy-on-most-efficient-solution-simple-c-gdkq | Intuition\n Describe your first thoughts on how to solve this problem. \n## Cost simplified\nAccording to the problem description:\n\ncost = maximum price sum - | hero080 | NORMAL | 2023-05-26T21:59:00.207548+00:00 | 2023-05-26T21:59:00.207591+00:00 | 284 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n## Cost simplified\nAccording to the problem description:\n```\ncost = maximum price sum - minimum price sum\n```\nHowever, once you calm down you will notice that the `minimum price sum` is simply the price of the root.\nTherefore the `cost` we are looking for is simply the maximum price sum of a path starting from the root but excluding the root itself.\n\n## It is a Tree\nThe problem specifies that the graph is a *tree*, which means we do not need to do the standard DFS, but only need to do a much simplier version of it: **post-order tree travesal**.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe traverse the tree and collecting 3 pieces of information:\n * The max price sum path starting from the (subtree) root (`type I path`)\n * The max price sum path starting from the (subtree) root but *not* ending at a leaf (`type II path`)\n * The best answer for this subtree.\n\nThese can be calculated pretty easily recursively.\n * Best `type I path` is the max of children\'s `type I path` plus root `price`.\n * Best `type II path` is also simply the max of children\'s `type I path` plus root `price`, except when this root itself is a leaf, in which case this is 0.\n * `answer` for all children is already resolved. For new answer that goes through this root node: We pick one child with `type I path` and *another* child with `type II path` and add them together as well as the root price. Care must be taken when handling edge cases:\n - This is a leaf node: no new answer avaialbe.\n - Only a single child node exists, the new answer is simply the child\'s `type II path`.\n - best children `type I path` and `type II path` belong to the same child: Take the second best into account.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$\\Theta(N)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$\\Theta(N)$$\n\n# Code\n```\nstruct TwoMax {\n int id_best = -1;\n int best = 0;\n int id_second = -1;\n int second = 0;\n\n void Update(int id, int value) {\n if (value <= second) {\n return;\n }\n if (value <= best) {\n id_second = id;\n second = value;\n return;\n }\n // Now value > best\n id_second = id_best;\n second = best;\n id_best = id;\n best = value;\n }\n};\n\nstruct TreeWalker {\n const vector<vector<int>>& graph;\n const vector<int>& prices;\n\n // Returns <type I path, type II path>\n // type I path: a path from this node to a leaf.\n // type II path: a path from this node to a non-leaf node.\n pair<int, int> FindPathDown(int node, int parent, int& answer) {\n const vector<int>& adjs = graph[node];\n const int price = prices[node];\n const int children_count = adjs.size() - (parent == -1 ? 0 : 1);\n if (children_count == 0) {\n // leaf\n return {price, 0};\n }\n TwoMax path1;\n TwoMax path2;\n for (int child : adjs) {\n if (child == parent) {\n continue;\n }\n auto [p1, p2] = FindPathDown(child, node, answer);\n path1.Update(child, p1);\n path2.Update(child, p2);\n }\n int new_answer = price;\n if (children_count == 1) {\n new_answer += path2.best;\n } else if (path1.id_best != path2.id_best) {\n new_answer += path1.best + path2.best;\n } else {\n new_answer += max(path1.best + path2.second, path1.second + path2.best);\n }\n answer = max(answer, new_answer);\n // cout << "#" << node << ": " << path1.best + price << ", " << path2.best + price << endl;\n return {path1.best + price, path2.best + price};\n }\n};\n\nvector<vector<int>> BuildGraph(int n, const vector<vector<int>>& edges) {\n vector<vector<int>> graph(n);\n for (const vector<int>& edge : edges) {\n int a = edge[0];\n int b = edge[1];\n graph[a].push_back(b);\n graph[b].push_back(a);\n }\n return graph;\n}\n\nclass Solution {\npublic:\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n if (n == 1) { return 0; }\n vector<vector<int>> graph = BuildGraph(n, edges);\n TreeWalker walker{.graph = graph, .prices = price};\n int answer = 0;\n auto [p1, p2] = walker.FindPathDown(0, -1, answer);\n return max(p1 - price[0], answer);\n }\n};\n``` | 2 | 0 | ['Tree', 'C++'] | 1 |
difference-between-maximum-and-minimum-price-sum | C++ || EASY CODE || REROOTING || SIMPLE APPROACH | c-easy-code-rerooting-simple-approach-by-oyu9 | Intuition\nBasically we will do two DFS calls.\n\n1) To find the max path from zero.\n\n2) we will have three things to find to get the max path for any node.\n | user3488Hj | NORMAL | 2023-02-14T13:14:56.312884+00:00 | 2023-02-14T13:14:56.312918+00:00 | 460 | false | # Intuition\nBasically we will do two DFS calls.\n\n1) To find the max path from zero.\n\n2) we will have three things to find to get the max path for any node.\n a) sum[x].\n b) parent\'s subtree that is having max path sum (other than subtree we are iterating).\n c) Grand parent\'s that subtree that is having max path sum (other than subtree we are iterating).\n\nAns will be maximum of all this three + price[node], if not included.\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution {\npublic:\n void dfs2(vector<vector<int>>& adj,vector<long long>&sum,vector<int>&vis,int u,vector<int>&price,vector<long long>& dist,long long par)\n {\n vis[u]=1;\n long long max1=0;\n long long max2=0;\n for(auto x:adj[u])\n {\n if(vis[x]==0)\n {\n if(sum[x]>=max1)\n {\n max2=max1;\n max1=sum[x];\n }\n else if(sum[x]>max2)\n max2=sum[x];\n }\n }\n \n long long calc=0;\n for(auto x:adj[u])\n { \n if(vis[x]==0)\n {\n if(max1 == sum[x]) {\n long long temp = max(max2+price[u]+price[x], sum[x]);\n dist[x] = max(temp, price[u]+par+price[x]);\n dfs2(adj,sum,vis,x,price,dist,max(max2,par)+price[u]);\n }else {\n long long temp = max(max1+price[u]+price[x], sum[x]);\n dist[x] = max(temp, price[u]+par+price[x]);\n dfs2(adj,sum,vis,x,price,dist,max(max1,par)+price[u]); \n }\n } \n }\n }\n long long dfs1(vector<vector<int>>& adj,vector<long long>&sum,vector<int>&vis,int u,vector<int>&price)\n {\n vis[u]=1;\n long long val=0;\n long long ans=0;\n for(auto x:adj[u])\n { \n if(vis[x]==0)\n {\n val=dfs1(adj,sum,vis,x,price); \n ans=max(ans,val);\n }\n }\n \n sum[u]=ans+price[u];\n return sum[u];\n }\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n \n vector<long long>sum(n,0);\n vector<vector<int>>adj(n,vector<int>());\n for(int i=0;i<edges.size();i++)\n {\n adj[edges[i][0]].push_back(edges[i][1]);\n adj[edges[i][1]].push_back(edges[i][0]);\n }\n vector<int>vis(n,0);\n dfs1(adj,sum,vis,0,price);\n vector<int>vis2(n,0);\n vector<long long>dist(n,0);\n dfs2(adj,sum,vis2,0,price,dist,0);\n long long calc=0;\n dist[0] = sum[0];\n for(int i=0;i<n;i++)\n {\n // cout << dist[i] << " ";\n calc=max(calc,dist[i]-price[i]);\n }\n return calc;\n }\n};\n\n\n\n``` | 2 | 0 | ['Binary Tree', 'C++'] | 1 |
difference-between-maximum-and-minimum-price-sum | C++| Root Shifting | O(N) | c-root-shifting-on-by-kumarabhi98-px6x | \nclass Solution {\npublic:\n long long ans = 0;\n int dfs(vector<vector<int>>& nums,vector<int>& val,vector<long long>& sum,int in,int p){\n sum[i | kumarabhi98 | NORMAL | 2023-01-23T10:49:30.644533+00:00 | 2023-01-23T10:49:30.644568+00:00 | 479 | false | ```\nclass Solution {\npublic:\n long long ans = 0;\n int dfs(vector<vector<int>>& nums,vector<int>& val,vector<long long>& sum,int in,int p){\n sum[in] = val[in];\n long long re = 0;\n for(int i = 0; i<(int)nums[in].size();++i){\n int j = nums[in][i];\n if(j!=p){\n long long k = dfs(nums,val,sum,j,in);\n re = max(re,k);\n }\n }\n return sum[in] = sum[in]+re;\n }\n void dfs2(vector<vector<int>> &nums,vector<int>& val,vector<long long>& sum,int in,int p,long long psum){\n psum+=val[in];\n ans = max(ans,max(psum,sum[in])-val[in]);\n priority_queue<pair<long long,long long>> q;\n for(int i = 0; i<nums[in].size();++i){\n int j = nums[in][i];\n if(j!=p){\n q.push({val[in]+sum[j],j});\n }\n }\n for(int i = 0; i<nums[in].size();++i){\n int j = nums[in][i];\n if(j!=p && q.size()){\n long long k = psum;\n if(q.top().second==j){\n pair<int,int> p = q.top(); q.pop();\n if(q.size()) k = max(k,q.top().first);\n q.push(p);\n }\n else k = max(k,q.top().first);\n dfs2(nums,val,sum,j,in,k);\n }\n }\n }\n long long maxOutput(int n, vector<vector<int>>& arr, vector<int>& cost) {\n vector<vector<int>> nums(n+1);\n for(int i = 0; i<arr.size(); ++i){\n nums[arr[i][0]].push_back(arr[i][1]);\n nums[arr[i][1]].push_back(arr[i][0]);\n }\n vector<long long> dp(n+1,0);\n dfs(nums,cost,dp,0,-1);\n dfs2(nums,cost,dp,0,-1,0);\n return ans;\n }\n};\n``` | 2 | 0 | ['Dynamic Programming', 'Tree', 'Depth-First Search', 'Recursion', 'C'] | 0 |
difference-between-maximum-and-minimum-price-sum | thought process, 1 dfs, O(n) | thought-process-1-dfs-on-by-jimhorng-omvu | (1) intuitively, try every node as root, find max cost of each path from root\n\n(2) since all nodes\'s price is positive, so minimum path sum will be the root | jimhorng | NORMAL | 2023-01-18T13:59:39.939463+00:00 | 2023-01-21T00:46:17.795708+00:00 | 366 | false | (1) intuitively, try every node as root, find max cost of each path from root\n\n(2) since all nodes\'s price is positive, so minimum path sum will be the root itself, and problems become finding max sum of each path from root substract root\'s price.\nwe can do that with a single dfs, where each node returns the max path sum. time: `n`\n```\n 2:7*\n / \n 1:8*\n / \\\n 0:9 3:6*\n / \\\n 4:10* 5:5\n```\n(3) combining (1), (2), time:`O(n*n)`\n\n(4) can we re-use information from single dfs?\n\n(5) as we can observe, if we start from `0` as root, when we get to `1`, we can have information of each max sum path of childs, and each node can be root, so we can see if these paths can form paths of nodes within path as roots\n```\n 0\n \\\n 1* <-\n / \\ \n 2* 3*\n / \\\n 4* 5\n```\n* cases\n```\ncase 1 case 2 case 3 case 4\n 0 0 0 0\n \\ \\ \\ \\ \n 1r <- 1* <- 1r <- 1* <-\n / \\ / \\ / \\ / \\\n 2 3* 2 3* 2 3* 2 3r \n / \\ / \\ / \\ / \\\n 4* 5 4r 5 4 5 4 5\n\ncase 5 case 6 case 7 case 8\n 0 0 0 0\n \\ \\ \\ \\ \n 1r <- 1* <- 1* <- 1* <-\n / \\ / \\ / \\ / \\\n 2* 3 2r 3 2r 3* 2* 3r \n / \\ / \\ / \\ / \\\n 4 5 4 5 4 5 4 5\n\ncase 9 case 10\n 0 0\n \\ \\\n 1* <- 1* <-\n / \\ / \\\n 2r 3* 2* 3*\n / \\ / \\\n 4* 5 4r 5\n```\n\n(6) since we already got max sum path from all childs, the sum of merging these max paths to form new paths(case 9,10) will be larger than any other cases, so that they can be skipped\n\n(7) if there\'s only 1 path from the only child, that sum path will be max. e.g.\n```\ncase 11 case 12\n 0r <- 0* <-\n \\ \\\n 1* 1* \n / \\ / \\\n 2 3* 2 3*\n / \\ / \\\n 4* 5 4r 5\n```\n\n(8) to sum up (6)(7), we can only consider merged max sum path from childs for each node as max cost candidate\n\n(9) to ensure we consider max sum path with ending node as root and non-root from childs, we need to record both cases in each node, \nalso, in merging process, we need to ensure both path are from different child.\nwe can do that as recording max 2 paths of 2 cases if max of both cases are overlapped, and do merging as "max path with ending node as root" with "2nd max path with ending node as non-root"\ne.g. \n```\n a) + d) b) + c)\n 0* 0*\n / \\ / \\\n 1* 2* 1* 2*\n / \\ / \\\n 3r 4* 3* 4r\n\nassuming:\na) max sub path contain root, 1-3\nb) max sub path not contain root, 1-3\nc) 2nd max sub path contain root, 2-4\nd) 2nd max sub path not contain root, 2-4\n\n```\n\n(10) so each node only process once and 2 cases (case 9,10 or case 11,12) is required, so time:`O(n)` = `2n`\n\n(11) to simplify code, although, processing more candidate paths, we can calculate "max path with ending node as root" by adding current node with child path and store for later merging while iterating childs, this can ensure we are merging sum paths of different child and including max ones, same applies to non-root paths.\ne.g.\n```\n 0*\n / | \\\n 1r 2 3\n ^\ncurrent child:1 \nprevious max path=none, merge as 1-0\n\n 0*\n / | \\\n 1r 2* 3\n - ^\ncurrrent child:2\nprevious max path=1, merge as 1-0-2\n\n 0*\n / | \\\n 1 2r 3*\n - - ^\ncurrrent child:3\nprevious max path=2, merge as 2-0-3\n```\n\n\n# Code\n(9)\n```\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n \n def maintain_2_max_paths(sum_path, sum_path_maxs, node):\n if len(sum_path_maxs) == 2 and sum_path > sum_path_maxs[0][0]:\n heapq.heappop(sum_path_maxs)\n if len(sum_path_maxs) < 2:\n heapq.heappush(sum_path_maxs, (sum_path, node))\n\n def dfs(node, root, edges_dict, visited):\n """ ret: sum_path_leaf_max, sum_path_root_max """\n sum_path_sub_leaf_maxs = [] # list[i]=(sum_path_sub_leaf_max, node_nx)\n sum_path_sub_root_maxs = []\n for node_nx in [ node_nx for node_nx in edges_dict[node] if node_nx not in visited ]:\n visited.add(node_nx)\n sum_path_sub_leaf, sum_path_sub_root = dfs(node_nx, root, edges_dict, visited)\n maintain_2_max_paths(sum_path_sub_leaf, sum_path_sub_leaf_maxs, node_nx)\n maintain_2_max_paths(sum_path_sub_root, sum_path_sub_root_maxs, node_nx)\n # cur(root/leaf)\n if len(sum_path_sub_root_maxs) == 0:\n return price[node], 0\n sum_path_sub_root_max1, node_path_sub_root_max1 = sum_path_sub_root_maxs[-1]\n sum_path_sub_leaf_max1, node_path_sub_leaf_max1 = sum_path_sub_leaf_maxs[-1]\n sum_path_sub_root_max2, node_path_sub_root_max2 = sum_path_sub_root_maxs[0]\n sum_path_sub_leaf_max2, node_path_sub_leaf_max2 = sum_path_sub_leaf_maxs[0]\n # cur(root/leaf) + sub(root/leaf)\n if len(sum_path_sub_root_maxs) == 1 and node == root:\n self.cost_max = max(self.cost_max, 0 + sum_path_sub_leaf_max1)\n self.cost_max = max(self.cost_max, price[node] + sum_path_sub_root_max1)\n # sub(root/leaf) + cur + sub(root/leaf)\n elif len(sum_path_sub_root_maxs) == 2:\n # path of max sub root != max sub leaf\n if node_path_sub_root_max1 != node_path_sub_leaf_max1:\n self.cost_max = max(self.cost_max, sum_path_sub_root_max1 + price[node] + sum_path_sub_leaf_max1)\n # path of max sub root == max sub leaf\n else:\n self.cost_max = max(self.cost_max, sum_path_sub_root_max1 + price[node] + sum_path_sub_leaf_max2)\n self.cost_max = max(self.cost_max, sum_path_sub_root_max2 + price[node] + sum_path_sub_leaf_max1)\n return sum_path_sub_leaf_max1+price[node], sum_path_sub_root_max1+price[node]\n \n self.cost_max = 0\n edges_dict = defaultdict(set)\n for v1, v2 in edges:\n edges_dict[v1].add(v2)\n edges_dict[v2].add(v1)\n \n visited = {0}\n dfs(0, 0, edges_dict, visited)\n return self.cost_max\n```\n\n(11)\n```\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n \n def dfs(node, edges_dict, visited):\n """ ret: sum_path_root, sum_path_leaf """\n sum_path_root_max, sum_path_leaf_max = 0, price[node]\n for node_nx in edges_dict[node]:\n if node_nx in visited:\n continue\n visited.add(node_nx)\n sum_sub_path_root, sum_sub_path_leaf = dfs(node_nx, edges_dict, visited)\n # sub path as root + (cur + max of other sub path as leaf)\n self.cost_max = max(self.cost_max, sum_sub_path_root + sum_path_leaf_max)\n # sub path as leaf + (cur + max of other sub path as root)\n self.cost_max = max(self.cost_max, sum_sub_path_leaf + sum_path_root_max)\n sum_path_root_max = max(sum_path_root_max, sum_sub_path_root + price[node])\n sum_path_leaf_max = max(sum_path_leaf_max, sum_sub_path_leaf + price[node])\n return sum_path_root_max, sum_path_leaf_max\n \n # main\n self.cost_max = 0\n edges_dict = defaultdict(set)\n for v1, v2 in edges:\n edges_dict[v1].add(v2)\n edges_dict[v2].add(v1)\n \n visited = {0}\n dfs(0, edges_dict, visited)\n return self.cost_max\n``` | 2 | 0 | ['Python'] | 1 |
difference-between-maximum-and-minimum-price-sum | [Python] DFS traverse, similar to the maximum path sum problem; Explained | python-dfs-traverse-similar-to-the-maxim-d3e1 | This problem is similar to the "maximum path sum" problem.\n\nWe pick any node, and DFS traverse the graph.\n\nFor each of the visiting node, we need to get (1) | wangw1025 | NORMAL | 2023-01-17T04:38:14.506056+00:00 | 2023-01-17T04:38:14.506113+00:00 | 495 | false | This problem is similar to the "maximum path sum" problem.\n\nWe pick any node, and DFS traverse the graph.\n\nFor each of the visiting node, we need to get **(1) the maximum path sum with the end node value; and (2) the maximum path sum without the end value**.\n\nSee the details in code:\n\n```\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n # it is the same problem as the finding the maximum path sum of a tree\n \n # step 1, build the graph\n self.G = collections.defaultdict(list)\n for s, e in edges:\n self.G[s].append(e)\n self.G[e].append(s)\n\n self.visited = set()\n self.price = price\n self.ans = 0\n\n # step 2, start from a random node and DFS traverse the graph\n # the maximum path sum will be updated during the traversal, and we can\n # return the result after the traversal is done.\n self.dfs(0)\n \n # Since we are using the min heap to track the maximum, we need to return - self.ans\n return -self.ans\n\n \n def dfs(self, idx):\n self.visited.add(idx)\n\n ps_f_list, ps_p_list = [], []\n\n for nidx in self.G[idx]:\n # for each visiting child we need to get:\n # (1) the maximum path sum with the end node\n # (2) the maximum path sum without the end node\n # We are calculating the difference between maximum path sum and minimum path sum,\n # the price is always postive, therefore, the minimum path sum is always the root value. When we find a path sum, the maximum difference is the path sum - root value.\n # The root value can be at any end of this path.\n # Thus, we need to track two path sum: one is with the end node value, one is not.\n if nidx not in self.visited:\n ps_full, ps_partial = self.dfs(nidx)\n heapq.heappush(ps_f_list, (ps_full, nidx))\n heapq.heappush(ps_p_list, (ps_partial, nidx))\n\n max_val = 0\n if len(ps_f_list) == 1:\n ps_f_max, _ = heapq.heappop(ps_f_list)\n ps_p_max, _ = heapq.heappop(ps_p_list)\n max_val = min(ps_f_max, ps_p_max - self.price[idx])\n fp_max, pp_max = ps_f_max - self.price[idx], ps_p_max - self.price[idx]\n elif len(ps_f_list) > 1:\n ps_f_max, fm_idx = heapq.heappop(ps_f_list)\n ps_p_max, pm_idx = heapq.heappop(ps_p_list)\n if fm_idx != pm_idx:\n max_val = ps_f_max + ps_p_max - self.price[idx]\n fp_max, pp_max = ps_f_max - self.price[idx], ps_p_max - self.price[idx]\n else:\n # get the second bigest price\n ps_f_max_2, _ = heapq.heappop(ps_f_list)\n ps_p_max_2, _ = heapq.heappop(ps_p_list)\n max_val = min(ps_f_max + ps_p_max_2, ps_f_max_2 + ps_p_max) - self.price[idx]\n fp_max, pp_max = ps_f_max - self.price[idx], ps_p_max - self.price[idx]\n else:\n fp_max, pp_max = -self.price[idx], 0\n\n if max_val < self.ans:\n self.ans = max_val\n\n return fp_max, pp_max\n``` | 2 | 0 | ['Depth-First Search', 'Python3'] | 1 |
difference-between-maximum-and-minimum-price-sum | Python dfs solution | python-dfs-solution-by-vincent_great-8jag | \ndef maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n\tself.ans, d = 0, defaultdict(list)\n\tfor u, v in edges:\n\t\td[u].append(v)\ | vincent_great | NORMAL | 2023-01-15T05:36:34.142620+00:00 | 2023-01-19T18:26:48.766369+00:00 | 120 | false | ```\ndef maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n\tself.ans, d = 0, defaultdict(list)\n\tfor u, v in edges:\n\t\td[u].append(v)\n\t\td[v].append(u)\n\n\tdef dfs(i, fi):\n\t\tmx1, mx2 = price[i], 0\n\t\tfor x in d[i]:\n\t\t\tif x != fi:\n\t\t\t\ts1, s2 = dfs(x, i)\n\t\t\t\tself.ans = max(self.ans, mx1 + s2, mx2 + s1)\n\t\t\t\tmx1 = max(mx1, s1 + price[i])\n\t\t\t\tmx2 = max(mx2, s2 + price[i])\n\t\treturn mx1, mx2\n\n\tdfs(0, -1)\n\treturn self.ans\n``` | 2 | 1 | [] | 1 |
difference-between-maximum-and-minimum-price-sum | O(n) | Re-rooting | c++ | on-re-rooting-c-by-betoscl-aqwj | Intuition\nprecalculate the best paths if we had 0 as root and then re-root and update those values \u200B\u200Bin $O(1)$\n\n# Approach\nFirst we need to find t | BetoSCL | NORMAL | 2023-01-15T04:33:25.805321+00:00 | 2023-01-15T04:33:25.805378+00:00 | 724 | false | # Intuition\nprecalculate the best paths if we had 0 as root and then re-root and update those values \u200B\u200Bin $O(1)$\n\n# Approach\nFirst we need to find the answer for root 0, so we keep a kind of $DP$ that says the best answer for each node if we start from there and just go down, with this $DP$ the answer will be the best of its children for each node $u$ since we will update the values \u200B\u200Bas if the node $u$ were the root\nThen it walks the tree with a dfs and tries to update said DP in an optimal way.\n\nTo do the re-root when we are going to travel to a node, we first have to update our DP value, for this there are 2 possible candidates to create the new best path from node $u$, the best child that is not the node we are going to, and our father if we have\n\n# Complexity\n- Time complexity:\n$O(n)$\n\n# Code\n```\nclass Solution {\npublic:\n long long ans = 0;\n vector<int> graph[100007];\n vector<long long> best;\n long long dfs_sz(int u,int p,vector<int> &pr){\n long long mx = 0;\n for(auto v:graph[u]){\n if(v ==p)continue;\n mx = max(mx,dfs_sz(v,u,pr));\n }\n best[u] = mx;\n return best[u]+pr[u];\n }\n \n void dfs(int u,int p ,vector<int> &pr){\n vector<pair<long long,int>> A;\n for(auto v:graph[u]){\n A.push_back({best[v]+pr[v],v});\n }\n \n sort(A.rbegin(),A.rend());\n if(A.size())\n ans = max(ans,A[0].first);\n \n for(auto v:graph[u]){\n if(v == p)continue;\n long long last = best[u];\n long long nwBest = 0;\n if(v ==A[0].second && A.size()>1){\n nwBest += A[1].first;\n }\n else if(v != A[0].second){\n nwBest += A[0].first;\n }\n if(p !=-1){\n nwBest = max(nwBest,best[p]);\n }\n \n best[u] = nwBest;\n dfs(v,u,pr);\n \n best[u] = last;\n }\n \n }\n \n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n best.resize(n);\n for(int i = 0;i<n-1;i++){\n int u = edges[i][0];\n int v = edges[i][1];\n graph[u].push_back(v);\n graph[v].push_back(u);\n }\n dfs_sz(0,-1,price);\n dfs(0,-1,price);\n return ans;\n }\n};\n``` | 2 | 1 | ['C++'] | 0 |
difference-between-maximum-and-minimum-price-sum | [Python3] dfs | python3-dfs-by-ye15-uf5g | \n\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n tree = [[] for _ in range(n)]\n for u, v | ye15 | NORMAL | 2023-01-15T04:16:58.696932+00:00 | 2023-01-15T04:16:58.696973+00:00 | 394 | false | \n```\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n tree = [[] for _ in range(n)]\n for u, v in edges: \n tree[u].append(v)\n tree[v].append(u)\n \n def dfs(u, p): \n """Return """\n nonlocal ans\n include = [] # include leaf value \n exclude = [] # exclude leaf value\n for v in tree[u]:\n if v != p: \n x, y = dfs(v, u)\n include.append((x+price[u], v))\n exclude.append((y+price[u], v))\n if not include: \n include = [(price[u], u)]\n exclude = [(0, u)]\n if len(include) == 1: ans = max(ans, include[0][0] - price[u], exclude[0][0])\n else: \n include.sort(reverse=True)\n for e, v in exclude: \n if v != include[0][1]: cand = e + include[0][0] - price[u]\n else: cand = e + include[1][0] - price[u]\n ans = max(ans, cand)\n return include[0][0], max(exclude)[0]\n \n ans = 0 \n dfs(0, -1)\n return ans \n``` | 2 | 1 | ['Python3'] | 0 |
difference-between-maximum-and-minimum-price-sum | C++ | 2 DFS | Pre-calculate for root 0 | c-2-dfs-pre-calculate-for-root-0-by-kena-jxf1 | Code | kenA7 | NORMAL | 2025-04-01T04:54:57.680228+00:00 | 2025-04-01T04:54:57.680228+00:00 | 19 | false |
# Code
```cpp []
class Solution {
public:
#define ll long long
vector<ll>maxCost;
ll calculateCostForRoot0(int u,int p, vector<vector<int>>&g,vector<int>& price)
{
ll res=0;
for(auto &v:g[u])
{
if(v==p)
continue;
res=max(res,calculateCostForRoot0(v,u,g,price));
}
res+=price[u];
return maxCost[u]=res;
}
ll maxResult;
void dfs(int u, int p, vector<vector<int>>&g,vector<int>& price, ll upperMax)
{
maxResult=max(upperMax, maxResult);
maxResult=max(maxResult, maxCost[u]-price[u]);
ll maxChild=0,secondMaxChild=0,c1=0,c2=0;
for(auto &v:g[u])
{
if(v==p)
continue;
if(maxCost[v]>c1)
{
c2=c1;
secondMaxChild=maxChild;
c1=maxCost[v];
maxChild=v;
}
else if(maxCost[v]>c2)
{
c2=maxCost[v];
secondMaxChild=v;
}
}
upperMax+=price[u];
//Traverse
for(auto &v:g[u])
{
if(v==p)
continue;
ll nextUpperMax=upperMax;
if(v==maxChild)
nextUpperMax=max(nextUpperMax, c2+price[u]);
else
nextUpperMax=max(nextUpperMax, c1+price[u]);
dfs(v,u,g,price,nextUpperMax);
}
}
long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price)
{
vector<vector<int>>g(n);
maxCost.resize(n,0);
maxResult=0;
for(auto &e:edges)
{
g[e[0]].push_back(e[1]);
g[e[1]].push_back(e[0]);
}
calculateCostForRoot0(0,-1,g,price);
dfs(0,-1,g,price,0);
return maxResult;
}
};
``` | 1 | 0 | ['C++'] | 0 |
difference-between-maximum-and-minimum-price-sum | IN OUT DP || SIMPLE APPROACH || CSES Standard | in-out-dp-simple-approach-cses-standard-xbhnn | Intuition\n Describe your first thoughts on how to solve this problem. \nThe idea is same as of a CSES Tree Distance I problem.\n\nWe are here using in out dp i | asif_0077 | NORMAL | 2024-04-05T22:52:26.127524+00:00 | 2024-04-05T22:52:26.127541+00:00 | 40 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe idea is same as of a [CSES Tree Distance I](https://cses.fi/problemset/task/1132) problem.\n\nWe are here using in out dp in which we have in and out arrays by which we are at every node we have max path sum in its subtree using in array and max path sum out it(along root side) denoted by out\n \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWhile doing dfsIn we are populating in values simply \nthe main problem is in dfsOut in which we are first finding mx1 and mx2 which will tell apart from the out[par] in all the siblings of that is there any path which is giving maximum sum and if that path coincides with the same subtree of that parent node of which we are calculating int that case we use the value of mx2 in all other cases we use mx1 and then just update\n`out[child] = max(out[parent], longest) + prices[u]; `\nwhere longest is deciding which mx value to take.\n\nand at the end we just check for every node in that tree what is the maximm path sum \nCheck code for better understanding.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(N)\n\n# Code\n```\ntypedef long long int ll;\nclass Solution {\npublic:\n vector<vector<int>>g;\n vector<ll>prices;\n vector<ll>in,out;\n void dfsIn(int u, int par) {\n for(auto v : g[u]){\n if(v!=par){\n dfsIn(v,u);\n in[u] = max(in[u],in[v]);\n }\n }\n in[u] += prices[u];\n }\n void dfsOut(int u, int par){\n ll mx1 = -1,mx2 = -1;\n for(auto v : g[u]){\n if(v!=par){\n if(in[v]>=mx1){\n mx2 = mx1;\n mx1 = in[v] ;\n }\n else if(in[v]>mx2){\n mx2 = in[v];\n }\n }\n }\n for(auto neig : g[u]){\n if(neig!=par){\n ll longest = mx1;\n if(mx1==in[neig])longest = mx2;\n out[neig] = max(out[u], longest) + prices[u];\n dfsOut(neig,u);\n }\n }\n \n }\n long long maxOutput(int n, vector<vector<int>>& tree, vector<int>& price) {\n g.clear(), prices.clear(), in.clear(), out.clear();\n g.resize(n), prices.resize(n), in.resize(n), out.resize(n);\n for (auto e : tree) {\n g[e[0]].push_back(e[1]);\n g[e[1]].push_back(e[0]);\n }\n for (int j = 0; j < n; j ++) prices[j] = price[j];\n\n dfsIn(0,-1);\n dfsOut(0,-1);\n ll result = 0;\n\n for (int root = 0; root < n; root ++) {\n ll val = max (in[root], out[root]+prices[root]) - prices[root];\n result = max (result, val);\n }\n return result;\n }\n};\n``` | 1 | 0 | ['Dynamic Programming', 'Graph', 'C++'] | 0 |
difference-between-maximum-and-minimum-price-sum | DP ON TREES || SIMILAR TO TREE DISTANCE 1 | dp-on-trees-similar-to-tree-distance-1-b-8gzv | \n\nclass Solution {\npublic:\n vector<vector<int>>g;\n vector<long long>d,ans;\n void f1(int s,int p,vector<int>& pr){\n long long a=pr[s];\n | Agam_Raizada | NORMAL | 2024-03-11T20:41:25.470908+00:00 | 2024-03-11T20:41:25.470940+00:00 | 22 | false | \n```\nclass Solution {\npublic:\n vector<vector<int>>g;\n vector<long long>d,ans;\n void f1(int s,int p,vector<int>& pr){\n long long a=pr[s];\n for(int c:g[s]){\n if(c!=p){\n f1(c,s,pr);\n a=max(a,pr[s]+d[c]);\n }\n }\n d[s]=a;\n\n }\n void func(int s,int p,long long pa,vector<int>& pr){\n vector<long long>pre,suf;\n for(int c:g[s]){\n if(c!=p){\n pre.push_back(d[c]);\n suf.push_back(d[c]);\n }\n }\n \n for(int i=1;i<pre.size();i++){\n pre[i]=max(pre[i],pre[i-1]);\n }\n for(int i=suf.size()-2;i>=0;i--){\n suf[i]=max(suf[i],suf[i+1]);\n }\n int cn=0;\n for(int c:g[s]){\n if(c!=p){\n long long op1=(cn==0)?INT_MIN:pre[cn-1];\n long long op2=(cn==suf.size()-1)?INT_MIN:suf[cn+1];\n int par=pr[s]+max(pa,max(op1,op2));\n func(c,s,par,pr);\n cn++;\n\n }\n }\n ans[s]=max(pa,(pre.empty()?-1:pre.back()));\n }\n long long maxOutput(int n, vector<vector<int>>& e, vector<int>& pr) {\n g.resize(n+1);\n d.resize(n+1,0);\n ans.resize(n+1,0);\n for(int i=0;i<n-1;i++){\n g[e[i][0]].push_back(e[i][1]);\n g[e[i][1]].push_back(e[i][0]);\n }\n f1(0,-1,pr);\n func(0,-1,0,pr);\n long long a=0;\n for(auto it:ans) a=max(a,it);\n return a;\n\n \n }\n};\n``` | 1 | 0 | ['Dynamic Programming', 'Tree', 'C++'] | 0 |
difference-between-maximum-and-minimum-price-sum | C++ | Rerooting | c-rerooting-by-user4957x-zl33 | Intuition\nEasy to solve id rooted, so solve for a random root, and reroot the tree.\n\n# Approach\nRerooting\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Spa | user4957x | NORMAL | 2024-02-03T19:16:29.454019+00:00 | 2024-02-03T19:17:52.705622+00:00 | 25 | false | # Intuition\nEasy to solve id rooted, so solve for a random root, and reroot the tree.\n\n# Approach\nRerooting\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n vector<vector<int>> gr(n + 1);\n\n for(auto ed: edges) { \n gr[ed[0]].push_back(ed[1]);\n gr[ed[1]].push_back(ed[0]);\n }\n\n vector<pair<int, int>> dp(n, {0, 0});\n\n function<void(int, int)> dfs1 = [&](int curr, int par) {\n auto& [mx, mx2] = dp[curr];\n\n for(auto child: gr[curr]) {\n if(child == par) continue;\n dfs1(child, curr);\n mx2 = max(mx2, dp[child].first);\n if(mx2 > mx) swap(mx, mx2);\n }\n\n mx += price[curr], mx2 += price[curr];\n };\n \n \n\n int ans = 0;\n\n function<void(int, int)> dfs2 = [&](int curr, int par) {\n auto& [mx, mx2] = dp[curr];\n auto backup_curr = dp[curr];\n\n ans = max(ans, mx - price[curr]);\n\n for(auto child: gr[curr]) {\n if(child == par) continue;\n auto& [cmx, cmx2] = dp[child];\n auto backup_child = dp[child];\n //disconnect as parent\n if(mx == cmx + price[curr]) mx = mx2;\n //connect as child\n cmx2 = max(cmx2, mx + price[child]);\n if(cmx2 > cmx) swap(cmx, cmx2);\n\n dfs2(child, curr);\n\n //reset\n dp[child] = backup_child;\n dp[curr] = backup_curr;\n }\n };\n\n dfs1(0, 0);\n dfs2(0, 0);\n\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 1 |
difference-between-maximum-and-minimum-price-sum | 💡Rerooting Easy to understant solution | rerooting-easy-to-understant-solution-by-a6e0 | Intuition\n Describe your first thoughts on how to solve this problem. \nAll the best with your coding preparation, This is new approach so don\'t be discourage | omkarkawatgi | NORMAL | 2023-11-22T12:22:40.820831+00:00 | 2023-11-22T12:22:40.820860+00:00 | 47 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAll the best with your coding preparation, This is new approach so don\'t be discouraged if you were not able to solve it... Keep learning, keep growing. Let me know any doubts...\n \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long ans;\n void dfs1(int i,int parent,vector<pair<long long,long long>>& toptwo,vector<int> adj[],vector<int>& price){\n \n pair<long long,long long> p = toptwo[parent];\n // Update values before rerooting to another node\n if(i!=parent){\n long long x = p.first;\n if(x==toptwo[i].first+price[i])x = p.second;\n x += price[parent] ;\n // We will update toptwo values of current node if parent is providing better value\n if(x >= toptwo[i].first){\n toptwo[i].second = toptwo[i].first;\n toptwo[i].first = x;\n }\n else if(x > toptwo[i].second) toptwo[i].second = x;\n }\n \n ans = max(ans,toptwo[i].first);\n\n for(auto j:adj[i]){\n if(j!=parent)dfs1(j,i,toptwo,adj,price);\n }\n\n }\n long long dfs(int i,int parent,vector<pair<long long,long long>>& toptwo,vector<int> adj[],vector<int>& price){\n \n pair<long long,long long> p;\n p.first = 0; p.second = 0;\n for(auto j:adj[i]){\n if(j!=parent){\n long long x = dfs(j,i,toptwo,adj,price);\n // Storing toptwo values coming from all the child\n if(x>=p.first){\n p.second = p.first;\n p.first = x;\n }\n else if(x>p.second)p.second = x;\n }\n }\n toptwo[i] = p;\n // Return max value from child + price of current value\n return p.first+price[i];\n\n }\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n \n vector<pair<long long,long long>> toptwo(n);\n vector<int> adj[n];\n for(int i=0;i<n-1;i++){\n adj[edges[i][0]].push_back(edges[i][1]);\n adj[edges[i][1]].push_back(edges[i][0]);\n }\n ans = 0;\n dfs(0,-1,toptwo,adj,price);\n dfs1(0,0,toptwo,adj,price);\n return ans;\n }\n};\n``` | 1 | 0 | ['Tree', 'Depth-First Search', 'C++'] | 0 |
difference-between-maximum-and-minimum-price-sum | Re-rooting Tree dp || Happy Coding | re-rooting-tree-dp-happy-coding-by-vikas-b3bg | Intuition\nThis is a re-rooting tree dp problem \n\n# Approach\nfirst find the solution for any one node as a root ( eg. 0);\nthat is what dfs(0, -1) is finding | vikas58616 | NORMAL | 2023-08-05T22:40:48.960261+00:00 | 2023-08-05T22:40:48.960283+00:00 | 47 | false | # Intuition\nThis is a re-rooting tree dp problem \n\n# Approach\nfirst find the solution for any one node as a root ( eg. 0);\nthat is what dfs(0, -1) is finding \n\nthen we need to update the root that is done using dfs2(-1, 0, 0);\nfunction\nthe below implementation is a standard template for rerooting the tree\nstep to follow are \n1.) we are at root u , store the ans for this root\n2.) do some kind of preprocessing in sub-linear time so that we do not exceed O(N^2) bound ( Note : this step is difference bases on question)\n3.) change the roots to current nodees children\n here also note that we need to calculate the parent contribution for this child and pass it in the recursive call\n\nthats it for re-rooting \n\n# Code\n```\n#define ll long long\n\nclass Solution {\n vector<vector<ll>> g;\n vector<ll> prices;\n vector<ll> dp, ans;\n //dp[u] : store max path sum in the subtree of u;\npublic:\n ll dfs(int u, int p){\n ll maxi = 0LL;\n for(auto &v : g[u]){\n if(v == p)continue;\n ll childsum = dfs(v, u);\n maxi = max(maxi, childsum);\n }\n return dp[u] = maxi + prices[u];\n }\n\n void dfs2(int u, int p, ll parentSum){\n int c1 = -1; //stores the child having max sum;\n ll msum1 = 0, msum2 = 0; //store two max sum in childrens\n\n //just storing values of childrens (preprocessing step)\n for(auto &v : g[u]){\n if(v == p)continue;\n if(dp[v] > msum1){\n msum2 = msum1;\n msum1 = dp[v];\n c1 = v;\n }else if(dp[v] > msum2){\n msum2 = dp[v];\n }\n }\n\n //calculate the ans for this node as a root;\n ans[u] = max(msum1, parentSum) + (ll)prices[u] - (ll)prices[u]; //minSum path is only one node long\n\n //change root\n for(auto &v : g[u]){\n if(p == v)continue;\n //this if-else is for deciding parentSum\n if(v == c1){ \n ll ps = max(msum2, parentSum) + (ll)prices[u];\n dfs2(v, u, ps);\n }else{\n ll ps = max(msum1, parentSum) + (ll)prices[u];\n dfs2(v, u, ps);\n }\n }\n \n }\n\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n g.clear(), prices.clear(), dp.clear(), ans.clear();\n g.resize(n), prices.resize(n), dp.resize(n), ans.resize(n);\n for(auto ed : edges){\n g[ed[0]].push_back(ed[1]);\n g[ed[1]].push_back(ed[0]);\n }\n\n for(int i=0; i<n; i++){\n prices[i] = price[i];\n }\n\n dfs(0, -1);\n dfs2(0, -1, 0);\n\n //find the max differene among all roots;\n ll res = 0;\n for(int i=0; i<n; i++){\n res = max(res, ans[i]);\n }\n return res;\n }\n};\n``` | 1 | 0 | ['Array', 'Dynamic Programming', 'Tree', 'Depth-First Search', 'C++'] | 0 |
difference-between-maximum-and-minimum-price-sum | O(n) || DFS || C++ | on-dfs-c-by-kavascgjmd39-7tza | Intuition\n Describe your first thoughts on how to solve this problem. \nThe question was difficult so if you cant do it is fine. I solved it after fixing vario | kavascgjmd39 | NORMAL | 2023-07-03T07:36:05.074506+00:00 | 2023-07-03T07:37:06.538676+00:00 | 55 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe question was difficult so if you cant do it is fine. I solved it after fixing various cases in O(n)\nIf i rewrite the question it is give me the sum of maxium path\nfrom the root node to leaf node without considering root node (as root node will be the minimum sum ), so let 0 be the root node \n\nSo the ans will be the maximum value of - (sum of path from any node to leaf + sum of from that node to another leaf without considering leaf ) \nBoth path should be different \n\n\nhere for node 1 we are considering the max of -\nmax( (sum of child 9 (without leaf ) + sum of child 3(with leaf )+ price[1]) , (sum of child 3 (without leaf ) + sum of child 9(with leaf )+ price[1]) )\n\nSo the difficult part in this question is we cant consider the max\nfrom same path, that is sum of child 9(with leaf) + sum of child(without leaf) \n\nBoth path should be different\n\nNow cases - \nCASE 1 - \n \n\nnow in the above image i can se as to get ans i cant only pass the max , and without max, sometime the need some could come big from the with less total sum ,so i need to pass leaf as well as maximum sum \nfor both the one with maximum total sum without lead node and \nthe one with total sum without leaf node\n\nSo will pass 4 values \nMaximum sum, Maximum sum leaf , Maximum sum without leaf node, Maximum sum without leaf\'s leaf node \n\nand will keep 4 values just to mark the node from which value is taken\nso that final answer dont have same path\n\n\n \n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n)\n\n\n# Code\n```\nclass Pair{\n public:\n long long a ;\n long long b ;\n long long la ; \n long long lb;\n Pair ( long long a, long long b , long long la, long long lb){\n this->a = a;\n this->b = b;\n this->la = la;\n this->lb = lb;\n }\n};\nclass Solution {\npublic:\n long long sol = 0;\n Pair maxoutput(vector<vector<int>>&g, vector<int>&price ,int st, int p){\n long long maxia = 0;\n long long maxib = 0;\n long long maxilfa = -1;\n long long maxilfb = -1;\n\n long long ansai = -1;\n long long ansbi = -1;\n\n long long anssai = -1;\n long long anssbi = -1;\n Pair ans (0,0 , -1, -1 );\n for(auto x : g[st]){\n if( x == p){\n continue;\n }\n Pair val = maxoutput(g, price, x, st );\n \n if(ans.a < val.a ){\n maxia = ans.a;\n maxilfa = ans.la;\n ans.a = val.a;\n ans.la = val.la;\n ansai = x;\n }\n else if (maxia < val.a){\n maxia = val.a;\n maxilfa = val.la;\n anssai = x; \n }\n\n if(ans.lb == -1 || ans.b - price[ans.lb] < val.b - price[val.lb]){\n maxib = ans.b;\n maxilfb = ans.lb;\n ans.b = val.b;\n ans.lb = val.lb;\n ansbi = x;\n }\n else if (maxilfb == -1 || maxib - price[maxilfb] < val.b - price[val.lb]){\n maxib = val.b;\n maxilfb = val.lb;\n anssbi = x;\n }\n\n }\n if(ansai == -1 && ansbi == -1){\n return Pair(price[st] , price[st] , st, st);\n }\n else if(ansai != ansbi){\n sol = max(sol , ans.a + ans.b - price[ans.lb] + price[st]);\n }\n else {\n sol = max(sol , ans.a);\n sol = max(sol, ans.b + price[st] - price[ans.lb]);\n if(maxilfb != -1)\n sol = max(sol , ans.a + maxib - price[maxilfb] + price[st]);\n if(maxilfa != -1){\n sol = max(sol, ans.b + maxia - price[ans.lb] + price[st]);\n }\n // cout <<maxia <<" "<<ans.b<<" h "<< maxilfa<<" ";\n }\n ans.a += price[st];\n ans.b += price[st];\n // cout << st<<" "<<sol <<" "<<ansai<<" "<<ansbi<<" "<<ans.a<<" "<<ans.b <<" ";\n return ans;\n }\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n vector<vector<int>>g(n);\n for(int i = 0 ; i<edges.size(); i++){\n int a = edges[i][0];\n int b = edges[i][1];\n g[a].push_back(b);\n g[b].push_back(a);\n }\n maxoutput(g, price, 0 ,0);\n return sol;\n\n\n }\n\n\n};\n``` | 1 | 0 | ['C++'] | 0 |
difference-between-maximum-and-minimum-price-sum | Easy DP On Tree C++ || Kartik Arora Style | easy-dp-on-tree-c-kartik-arora-style-by-n5yb0 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | dtom7628 | NORMAL | 2023-06-20T15:20:19.747829+00:00 | 2023-06-20T15:20:19.747846+00:00 | 216 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n \n vector<vector<int>> g;\n vector<int> dep,val,outdp;\n vector<int> ans;\n\n void dfs(int u,int par){\n for(auto v:g[u]){\n if(v==par) continue;\n dfs(v,u);\n dep[u]=max(dep[u],val[u]+dep[v]);\n }\n }\n\n void dfs2(int u,int par,int par_ans){\n vector<int> pre,suf;\n for(auto v:g[u]){\n if(v==par) continue;\n pre.push_back(dep[v]);\n suf.push_back(dep[v]);\n }\n int sz = pre.size();\n for(int i=1;i<sz;i++){\n pre[i] = max(pre[i],pre[i-1]);\n }\n for(int i=sz-2;i>=0;i--){\n suf[i] = max(suf[i],suf[i+1]);\n }\n int idx = 0;\n for(auto v:g[u]){\n if(v==par) continue;\n int op1 = idx==0 ? INT_MIN : pre[idx-1];\n int op2 = idx==sz-1 ? INT_MIN : suf[idx+1];\n int p = val[u]+max(par_ans,max(op1,op2));\n dfs2(v,u,p); \n idx++;\n }\n if(sz==0){\n ans[u] = max(par_ans,-1);\n return;\n }\n ans[u] = max(par_ans,pre[sz-1]);\n }\n\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n g.assign(n+1,vector<int>());\n ans.assign(n+1,0);\n for(auto it:edges){\n g[it[0]].push_back(it[1]);\n g[it[1]].push_back(it[0]);\n }\n val = price;\n dep = price;\n outdp = price;\n dfs(0,-1);\n dfs2(0,-1,0);\n return *max_element(ans.begin(),ans.end());\n }\n};\n``` | 1 | 0 | ['Dynamic Programming', 'Tree', 'Depth-First Search', 'C++'] | 0 |
difference-between-maximum-and-minimum-price-sum | Re rooting | O(N) clean code | re-rooting-on-clean-code-by-w2024-ds9r | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | w2024 | NORMAL | 2023-01-17T12:23:49.486899+00:00 | 2023-01-17T12:23:49.486936+00:00 | 1,041 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n Set<Integer>[] graph;\n long[][] dp; \n int[] price;\n long max = 0;\n public long maxOutput(int n, int[][] edges, int[] price) {\n this.price = price;\n graph = new HashSet[n];\n for (int i = 0; i < n; i++) {\n graph[i] = new HashSet<>();\n }\n for (int[] e : edges) {\n graph[e[0]].add(e[1]);\n graph[e[1]].add(e[0]);\n }\n dp = new long[n][2]; \n dfs(0, -1);\n for (int i = 0; i < n; i++) {\n max = Math.max(max, dp[i][0] - price[i]);\n }\n dfs1(0, -1); \n return max;\n }\n\n private void dfs(int cur, int pre) {\n dp[cur][0] = price[cur];\n for (int child : graph[cur]) {\n if (child == pre) {\n continue;\n }\n dfs(child, cur);\n long max = dp[child][0] + price[cur];\n if (max > dp[cur][0]) {\n dp[cur][1] = dp[cur][0];\n dp[cur][0] = max;\n } else if (max > dp[cur][1]) {\n dp[cur][1] = max;\n } \n }\n }\n\n private void dfs1(int cur, int pre) {\n for (int child : graph[cur]) { \n if (child == pre) {\n continue;\n }\n if (dp[cur][0] == dp[child][0] + price[cur]) {\n if (dp[child][0] > dp[cur][1] + price[child]) {\n dp[child][0] = dp[child][0];\n dp[child][1] = Math.max(dp[child][1], dp[cur][1] + price[child]);\n } else {\n dp[child][0] = dp[cur][1] + price[child];\n dp[child][1] = Math.min(dp[child][0], dp[cur][1] + price[child]);\n }\n } else {\n if (dp[child][0] > dp[cur][0] + price[child]) {\n dp[child][0] = dp[child][0];\n dp[child][1] = Math.max(dp[child][1], dp[cur][0] + price[child]);\n } else {\n dp[child][0] = dp[cur][0] + price[child];\n dp[child][1] = Math.min(dp[child][0], dp[cur][1] + price[child]);\n }\n }\n max = Math.max(max, dp[child][0] - price[child]);\n dfs1(child, cur);\n } \n }\n}\n``` | 1 | 0 | ['Java'] | 1 |
difference-between-maximum-and-minimum-price-sum | [Python] explanation of `DFS + cache` approach | python-explanation-of-dfs-cache-approach-dgpl | python\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n g = defaultdict(list)\n \n for | pbelskiy | NORMAL | 2023-01-16T21:58:51.300617+00:00 | 2023-01-16T22:00:35.099038+00:00 | 101 | false | ```python\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n g = defaultdict(list)\n \n for a, b in edges:\n g[a].append(b)\n g[b].append(a)\n \n @cache\n def dfs(i, p):\n r = 0\n\n for j in g[i]:\n if j == p:\n continue\n \n r = max(r, dfs(j, i) + price[j])\n\n return r\n\n """\n Here we just use DFS to get max sum from target node with\n cache which boost our search.\n \n min = price[i]\n result = dfs(i, 1) + price[i] - min\n \n DFS return sum without target node value, so we need to add it,\n also we need to substract minimum from path which supposed to be also\n node value, not last node because it\'s optimization, because we will process\n from last node to target in future.\n \n Example:\n [1 + 2 + 3] : (2 + 3) + 1 - 1\n DFS val min\n\n [3 + 2 + 1] : (2 + 1) + 3 - 3\n DFS val min\n \n So we just use result of DFS :-)\n """\n res = float(\'-inf\')\n for i in range(n):\n res = max(res, dfs(i, -1))\n\n return res\n``` | 1 | 0 | ['Depth-First Search', 'Memoization'] | 0 |
difference-between-maximum-and-minimum-price-sum | C++ DFS 100% Faster | c-dfs-100-faster-by-rook_lift-3by7 | \n#define ll long long int \nclass Solution {\npublic:\n ll ans=0;\n \n vector<ll> vec[100005];\n ll mx[100005];\n \n void dfs1(ll u, ll p , vector<int> | Rook_Lift | NORMAL | 2023-01-16T18:06:54.349814+00:00 | 2023-01-16T18:06:54.349859+00:00 | 323 | false | ```\n#define ll long long int \nclass Solution {\npublic:\n ll ans=0;\n \n vector<ll> vec[100005];\n ll mx[100005];\n \n void dfs1(ll u, ll p , vector<int>&a)\n {\n mx[u]=0;\n \n for(ll v:vec[u])\n {\n if(v==p) continue;\n dfs1(v,u,a);\n mx[u]=max(mx[u], mx[v]);\n }\n mx[u]+=a[u];\n }\n void dfs(ll u, ll p ,vector<int>&a ,ll above)\n {\n multiset<ll>st;\n st.insert(above);\n \n for(ll v:vec[u])\n {\n if(v==p) continue;\n st.insert(mx[v]);\n }\n for(ll v:vec[u])\n {\n if(v==p) continue;\n st.erase(st.find(mx[v]));\n ll o=0;\n if(st.size()) o= *(--st.end());\n dfs(v,u,a,o+a[u]);\n st.insert(mx[v]);\n }\n ans=max(ans,*(--st.end()));\n }\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& a) {\n \n for(vector<int>vv:edges)\n {\n vec[vv[0]].push_back(vv[1]);\n vec[vv[1]].push_back(vv[0]);\n }\n ans=0;\n dfs1(0,0,a);\n dfs(0,0,a,0);\n return ans;\n }\n};\n``` | 1 | 0 | [] | 0 |
difference-between-maximum-and-minimum-price-sum | [java] ✔ One of the easiest solution DFS + DP || Explanation | java-one-of-the-easiest-solution-dfs-dp-tk1yn | \npublic static long maxOutput(int n, int[][] edges, int[] price) {\n Map<String, Long> map = new HashMap<>();\n List<List<Integer>> adj = new Arr | atul-chaudhary | NORMAL | 2023-01-16T09:43:32.917635+00:00 | 2023-01-16T09:43:32.917684+00:00 | 107 | false | ```\npublic static long maxOutput(int n, int[][] edges, int[] price) {\n Map<String, Long> map = new HashMap<>();\n List<List<Integer>> adj = new ArrayList<>();\n for (int i = 0; i < n; i++) {\n adj.add(new ArrayList<>());\n }\n\n for (int i = 0; i < edges.length; i++) {\n int u = edges[i][0];\n int v = edges[i][1];\n adj.get(u).add(v);\n adj.get(v).add(u);\n String str1 = u+"|"+v;\n String str2 = v+"|"+u;\n map.put(str1, 0L);\n map.put(str2, 0L);\n }\n long ans = 0;\n for (int i = 0; i < n; i++) {\n long cur = dfs(adj, map, price, i, -1);\n ans = Math.max(ans, cur - price[i]);\n }\n return ans;\n }\n\n private static long dfs(List<List<Integer>> adj, Map<String, Long> map, int[] price, int node, int parent) {\n long max = 0;\n for (int it : adj.get(node)) {\n if (it != parent) {\n String str = node + "|" + it;\n long temp = map.get(str);\n if (temp == 0) {\n temp = dfs(adj, map, price,it, node);\n map.put(str, temp);\n }\n max = Math.max(max, temp);\n }\n }\n return max + price[node];\n }\n``` | 1 | 0 | ['Dynamic Programming', 'Depth-First Search', 'Java'] | 0 |
difference-between-maximum-and-minimum-price-sum | Java | two dfs | java-two-dfs-by-conchwu-rxwn | \n //2.two DFS\n //Runtime: 105ms 100%; Memory 99.1MB 100%\n //Time: O(N); Space: O(N);\n public long maxOutput(int n, int[][] edges, int[] price) { | conchwu | NORMAL | 2023-01-15T18:32:21.173075+00:00 | 2023-01-15T18:32:21.173119+00:00 | 526 | false | ```\n //2.two DFS\n //Runtime: 105ms 100%; Memory 99.1MB 100%\n //Time: O(N); Space: O(N);\n public long maxOutput(int n, int[][] edges, int[] price) {\n List<Integer>[] graph = new List[n];\n for (int i = 0; i < n; i++)\n graph[i] = new ArrayList<>();\n\n for(int[] edge: edges){\n graph[edge[0]].add(edge[1]);\n graph[edge[1]].add(edge[0]);\n }\n\n long[] counter = new long[n];\n //first dfs\n res2 = helper2_dfs(price, graph, 0, -1, counter);\n //second dfs: re-root\n helper2_dfs2(price, graph, 0, counter, new int[n]);\n return res2;\n }\n\n private long res2 = 0;\n private void helper2_dfs2(int[] price, List<Integer>[] graph, int node,\n long[] counter, int[] seen) {\n\n long tmpX = counter[node];\n seen[node] = 1;\n for (int neighbour : graph[node]) {\n if (seen[neighbour] == 1) continue;\n\n //root -> child\n long childCount = 0l;\n for (int child : graph[node]) {\n if (child == neighbour) continue;\n childCount = Math.max(childCount, price[child] + counter[child]);\n }\n counter[node] = childCount;\n\n //child -> root\n long tmpY = counter[neighbour];\n counter[neighbour] = Math.max(price[node] + childCount, counter[neighbour]);\n res2 = Math.max(res2, counter[neighbour]);\n\n seen[neighbour] = 1;\n helper2_dfs2(price, graph, neighbour, counter, seen);\n counter[neighbour] = tmpY;\n }\n counter[node] = tmpX;\n }\n\n private long helper2_dfs(int[] price, List<Integer>[] graph, int node, int parent, long[] counter) {\n long res = 0l;\n for (int neighbour: graph[node]) {\n if (neighbour == parent) continue;\n res = Math.max(res, price[neighbour] + helper2_dfs(price, graph, neighbour, node, counter));\n }\n return counter[node] = res;\n }\n\n\n\n //1.brute force | DFS\n //TLE\n //Time: O(N * N); Space: O(N)\n public long maxOutput_1(int n, int[][] edges, int[] price) {\n List<Integer>[] graph = new List[n];\n for (int i = 0; i < n; i++)\n graph[i] = new ArrayList<>();\n\n for(int[] edge: edges){\n graph[edge[0]].add(edge[1]);\n graph[edge[1]].add(edge[0]);\n }\n\n long res = 0;\n for (int i = 0; i < n; i++)\n res = Math.max(res, helper_dfs(price, graph, i, -1));\n\n return res;\n }\n\n private long helper_dfs(int[] price, List<Integer>[] graph, int node, int parent) {\n long res = 0;\n for (int neighbour: graph[node]) {\n if (neighbour == parent) continue;\n res = Math.max(res, price[neighbour] + helper_dfs(price, graph, neighbour, node));\n }\n return res;\n }\n``` | 1 | 0 | ['Depth-First Search', 'Java'] | 1 |
difference-between-maximum-and-minimum-price-sum | Rust DFS and Backtracking | rust-dfs-and-backtracking-by-xiaoping341-fis0 | Intuition\n Describe your first thoughts on how to solve this problem. \nUse DFS twice, with the first one to calculate maximum cost of each subtree, and the se | xiaoping3418 | NORMAL | 2023-01-15T17:00:01.968064+00:00 | 2023-01-16T11:47:02.625147+00:00 | 226 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse DFS twice, with the first one to calculate maximum cost of each subtree, and the second to calculate the answer with rerooting on a child. \n# Approach\n<!-- Describe your approach to solving the problem. -->\n1) Use dfs to calculate the maximum cost (array dist[]) choosen 0 as the root\n2) Set ret = dist[0] - price[0].\n3) Recursively call backtracking on u to refine ret with each child of u as the new root.\n4) In calculating the cost with the new root v, we only need to consider two of the three types of paths:\n a) paths from parent u to other nodes that are not v\'s siblings;\n b) paths from parent u to other siblings.\n c) Paths under the subtee rooted at v, these could be ignored since we are only interested in paths with biggest cost. \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N Log N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n# Code\n```\nuse std::collections::BTreeMap;\n\nimpl Solution {\n pub fn max_output(n: i32, edges: Vec<Vec<i32>>, price: Vec<i32>) -> i64 {\n let n = n as usize;\n let mut graph = vec![vec![]; n];\n\n for e in edges {\n let (u, v) = (e[0] as usize, e[1] as usize);\n graph[u].push(v);\n graph[v].push(u);\n }\n\n let mut dist = vec![0; n];\n Self::dfs(&graph, &price, &mut dist, 0, -1);\n\n let mut ret = dist[0] - price[0] as i64;\n Self::backtracking(&graph, &price, &dist, &mut ret, 0, -1, 0);\n \n ret\n }\n\n fn dfs(graph: &Vec<Vec<usize>>, price: &Vec<i32>, dist: &mut Vec<i64>, u: usize, p: i32) {\n dist[u] = price[u] as i64;\n\n for v in &graph[u] {\n if p == *v as i32 { continue }\n\n Self::dfs(graph, price, dist, *v, u as i32);\n dist[u] = dist[u].max(dist[*v] + price[u] as i64);\n }\n }\n\n fn backtracking(graph: &Vec<Vec<usize>>, price: &Vec<i32>, dist: &Vec<i64>, ret: &mut i64, u: usize, p: i32, p_max: i64) {\n let mut mp = BTreeMap::<i64, i32>::new();\n\n for v in &graph[u] {\n if p == *v as i32 { continue }\n \n *mp.entry(dist[*v]).or_insert(0) += 1;\n }\n\n for v in &graph[u] {\n if p == *v as i32 { continue }\n \n if *mp.get(&dist[*v]).unwrap() == 1 { mp.remove(&dist[*v]); }\n else { *mp.entry(dist[*v]).or_insert(0) -= 1; }\n\n let mut temp = price[u] as i64 + p_max;\n if mp.is_empty() == false { temp = temp.max(price[u] as i64 + *mp.keys().next_back().unwrap()); }\n *ret = (*ret).max(temp);\n Self::backtracking(graph, price, dist, ret, *v, u as i32, temp);\n \n *mp.entry(dist[*v]).or_insert(0) += 1;\n } \n }\n}\n``` | 1 | 0 | ['Rust'] | 0 |
difference-between-maximum-and-minimum-price-sum | Java DFS+Memoriazation with explanation | java-dfsmemoriazation-with-explanation-b-nnoy | Intuition\nThe idea that I have when seeing the problem is to use DFS. \n- Build an adjacent table(HashMap) to record the neighbor point for each node;\n- in th | XYH10022 | NORMAL | 2023-01-15T15:06:31.566899+00:00 | 2023-01-15T15:06:31.566942+00:00 | 392 | false | # Intuition\nThe idea that I have when seeing the problem is to use DFS. \n- Build an adjacent table(HashMap) to record the neighbor point for each node;\n- in the method of dfs, pass the current ndoe and its parent node(from where we traverse to current node)\n- \nBut the time complexity for it can be terrible since we need to start at every node to get the result. So I have two optimazation here\n1. only start dfs from a leaf node\n It is obviours that the path starts and end with leaf node.(If we start dfs from a none leaf node, we can get a longer path from one of its neighbor leaf node.)\n When we build a the adjacent table, we can record the degree of each node. Then we only start at nodes with degree 1\n\n2. Memorization\n We can have terrible time complexity in some cases. See the example below. \n\n In this example, we have two groups of nodes. Each time we start at a leaf node in the left group and traverse to right group, we need to go through every node on the right group. The time complexity come close to the case that we start dfs at every node.\n Then it brings me to the idea of memorization in dynamic programming. We can build a hashmap to record the previours path with its result. The good this here is that instead of using the entire path, we can just use the current node and parent node to represent the path.\n In the example above, say we have do dfs from node 0 to node1 to node6, and get the maximun result of going from node6 to all its leaf node in the first dfs. Then we have a map Pair(cur, parent) : res. Next time we start dfs at node2 and traverse to node1 then to node6, we don\'t need to try every cases in the right group.\n\n\n\n# Code\n```\nclass Solution {\n HashMap<Integer, List<Integer>> adj;\n int[] price;\n HashMap<Pair<Integer, Integer>, Long> memo = new HashMap<>();\n \n public long maxOutput(int n, int[][] edges, int[] price) {\n // edge case\n if(n == 1) return 0;\n \n adj = new HashMap<>();\n this.price = price;\n int[] degree = new int[n]; // record the degree of each node, those with degree 1 are leaf nodes\n \n for(int[] edge:edges){\n int a = edge[0];\n int b = edge[1];\n \n adj.putIfAbsent(a, new ArrayList<Integer>());\n adj.putIfAbsent(b, new ArrayList<Integer>());\n \n adj.get(a).add(b);\n adj.get(b).add(a);\n \n degree[a] ++;\n degree[b] ++;\n }\n \n long ans = 0;\n // dfs with leaf node(degree 1) \n for(int i=0; i<n; i++){\n ans = Math.max(ans, dfs(i, -1) - price[i]);\n }\n \n return ans;\n \n \n }\n \n public long dfs(int node, int pre){\n // reaches a leaf node\n if(adj.get(node).size() == 1 && adj.get(node).get(0) == pre){ \n return price[node];\n }\n \n //memorization\n Pair<Integer, Integer> pair = new Pair<>(node, pre);\n if(memo.containsKey(pair)) return memo.get(pair);\n \n long s = 0;\n for(Integer child:adj.get(node)){\n if(child == pre) continue;\n \n s = Math.max(s, dfs(child, node));\n \n }\n \n //update memo\n memo.put(pair, price[node] + s);\n \n return price[node] + s; \n }\n}\n``` | 1 | 0 | ['Java'] | 1 |
difference-between-maximum-and-minimum-price-sum | ✅ JavaScript || Easy || DFS || Memoization || Commented | javascript-easy-dfs-memoization-commente-s97d | \n\n\n```\n/*\n * @param {number} n\n * @param {number[][]} edges\n * @param {number[]} price\n * @return {number}\n /\nvar maxOutput = function(n, edges, price | Atikur-Rahman-Sabuj | NORMAL | 2023-01-15T14:48:04.572504+00:00 | 2023-01-15T14:48:31.440945+00:00 | 259 | false | \n\n\n```\n/**\n * @param {number} n\n * @param {number[][]} edges\n * @param {number[]} price\n * @return {number}\n */\nvar maxOutput = function(n, edges, price) {\n const m = new Array(n).fill(null).map(_=> new Map());\n for(const edge of edges){\n // initialize graph and path values with 0\n m[edge[0]].set(edge[1], 0);\n m[edge[1]].set(edge[0], 0);\n }\n let ans = 0;\n for(let i = 0 ; i < n ; i++){\n // run dfs for every node\n ans = Math.max(ans, dfs(i, -1) - price[i]);\n }\n return ans;\n \n //i -> current node, p -> parent node of i\n function dfs(i, p){\n let maxPath = 0;\n for(const child of m[i].keys()){\n if(child != p){\n // consider every adjacent node except parent\n let path = m[i].get(child);\n if(path === 0){\n // if price not calculated from i to child then calculate\n path = dfs(child, i);\n // memoize the calculation\n m[i].set(child, path); \n }\n maxPath = Math.max(maxPath, path);\n }\n }\n return maxPath + price[i];\n } \n}; | 1 | 0 | ['Depth-First Search', 'Memoization', 'JavaScript'] | 1 |
difference-between-maximum-and-minimum-price-sum | Three diffrent solutions | three-diffrent-solutions-by-g129512-q8jy | Solution 1\n- Enumerate the root nodes and find the maximum path sum from each root node to the leaf. \n- Pass the maximum path sum from parent branch during DF | g129512 | NORMAL | 2023-01-15T09:31:16.632404+00:00 | 2023-01-15T10:11:49.424142+00:00 | 455 | false | ## Solution 1\n- Enumerate the root nodes and find the maximum path sum from each root node to the leaf. \n- Pass the maximum path sum from parent branch during DFS. \n\n```\n\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n g=[[] for _ in range(n)]\n for a,b in edges:\n g[a].append(b)\n g[b].append(a)\n \n down_sum=[0]*n\n def dfs(i,p):\n r=price[i]\n for ch in g[i]:\n if ch==p:continue\n r=max(r,price[i]+dfs(ch,i))\n down_sum[i]=r\n return r\n dfs(0,-1)\n\n res=0\n def dfs2(i, p, parent_sum):\n nonlocal res\n all_branch=[(parent_sum, p)]\n for child in g[i]:\n if child==p:continue\n res = max(res, down_sum[child])\n all_branch.append((down_sum[child],child))\n \n all_branch.sort()\n for child in g[i]:\n if child==p:continue\n if all_branch[-1][1]==child:\n dfs2(child,i,all_branch[-2][0]+price[i])\n else:\n dfs2(child,i,all_branch[-1][0]+price[i])\n \n dfs2(0,-1,0)\n return res\n```\n\n## Solution 2\n- Enumerate the root nodes and find the maximum path sum from each root node to the leaf.\n- Use Memoized DFS to Eliminate Duplicate Computations\n\n```\n\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n g = [[] for _ in range(n)]\n for a, b in edges:\n g[a].append(b)\n g[b].append(a)\n\n @cache\n def dfs(i, p):\n r = 0\n for child in g[i]:\n if child==p: continue\n r = max(r, dfs(child, i)+price[child])\n return r\n\n return max(dfs(i,-1) for i in range(n))\n\n```\n\n## Solution 3\n- Enumerate simple paths in the tree.\n\n\nSimilar to [124. Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/), the simple path in the tree is enumerated by DFS once, and the currently traversed node does not have to be the endpoint of the path.\n\nWhen we visit a node, we consider the simple path througth current node.\n1. If current node has only one child branch, this node can be the path end.\n2. Else the path sum is the sum of two diffrent child branches, but one of the branche\'s sum need to be substracted by the weight of the leaf node. Then we find the maximum combination of two child branches.\n\nThe dfs function need to return two values, one is the maximum path sum in all child branches, another is the maximum sum of leaf-weight-removed path sum.\n\n```\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n if n==1:return 0\n\n g=[[] for _ in range(n)]\n for a,b in edges:\n g[a].append(b)\n g[b].append(a)\n\n res=0\n def dfs(i,p):\n nonlocal res\n sum_full=[]\n sum_sub=[]\n\n for ch in g[i]:\n if ch==p:continue\n full,sub=dfs(ch,i)\n sum_full.append((full+price[i],ch))\n sum_sub.append((sub+price[i],ch))\n\n if sum_full==[]:\n return (price[i],0)\n\n sum_full.sort(reverse=True)\n sum_sub.sort(reverse=True)\n\n if len(sum_full) == 1:\n res=max(res,max(sum_sub[0][0], sum_full[0][0] - price[i]))\n elif sum_full[0][1] != sum_sub[0][1]:\n res = max(res, sum_full[0][0] + sum_sub[0][0] - price[i])\n else:\n res = max(res, max(sum_sub[1][0]+sum_full[0][0], sum_sub[0][0]+sum_full[1][0])-price[i])\n\n return (sum_full[0][0],sum_sub[0][0])\n\n dfs(0,-1)\n return res\n\n\n```\n | 1 | 0 | ['Dynamic Programming', 'Depth-First Search'] | 0 |
difference-between-maximum-and-minimum-price-sum | Better than most voted | Easiest C++ | Brute Force Memoisation | better-than-most-voted-easiest-c-brute-f-g1r0 | Just use the brute force approach and memoise it using map.\nYes, it\'s that simple.\n\nNote: We are not using a dp[n][n] here because creating this only will t | AnujJadhav | NORMAL | 2023-01-15T05:26:16.258604+00:00 | 2023-01-15T05:27:21.051995+00:00 | 141 | false | Just use the brute force approach and memoise it using map.\nYes, it\'s that simple.\n\nNote: We are not using a ```dp[n][n]``` here because creating this only will take ```O(n^2)``` time, whereas not every node is going to have n childrens, this is where map comes handy.\n\nC++ code:\n```\nclass Solution {\npublic:\n \n map<pair<int, int>, long long> mp;\n \n long long getLongestPath(int src, int par, vector<vector<int>>& adj, vector<int>& price) {\n pair<int, int> key = {src, par+1};\n \n if(mp.find(key) != mp.end()) return mp[key];\n \n long long childMax = 0;\n for(auto it: adj[src]) {\n if(it == par) continue;\n \n long long val = getLongestPath(it, src, adj, price);\n childMax = max(childMax, val);\n }\n \n return mp[key] = childMax + price[src];\n }\n \n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n vector<vector<int>> adj(n);\n for(auto it: edges) {\n int u = it[0], v = it[1];\n adj[u].push_back(v);\n adj[v].push_back(u);\n }\n \n long long res = 0;\n \n for(int i = 0; i < n; i++) {\n long long path = getLongestPath(i, -1, adj, price);\n res = max(res, path - price[i]);\n }\n \n return res;\n }\n};\n``` | 1 | 0 | ['Dynamic Programming', 'Tree', 'Memoization'] | 0 |
difference-between-maximum-and-minimum-price-sum | damn just need one more line to get AK this week 😭 | damn-just-need-one-more-line-to-get-ak-t-jzrf | \n# Approach\n Describe your approach to solving the problem. \nuse dfs to build max price of each node\ndon\'t look at my code, its too complex and not elegant | ZhonghaoLuo | NORMAL | 2023-01-15T05:06:07.524409+00:00 | 2023-01-15T05:08:54.950336+00:00 | 431 | false | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nuse dfs to build max price of each node\ndon\'t look at my code, its too complex and not elegant\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n n2n = defaultdict(set)\n for a, b in edges:\n n2n[a].add(b)\n n2n[b].add(a)\n \n nodeandway2path = dict()\n visited = set()\n \n \n def dfs1(node):\n rtn = 0\n for nxt in n2n[node]:\n if nxt not in visited:\n visited.add(nxt)\n maxprice = dfs1(nxt)\n nodeandway2path[(node, nxt)] = maxprice + price[node]\n rtn = max(rtn, maxprice)\n return rtn + price[node]\n \n visited.add(0) \n dfs1(0)\n \n visited = set()\n \n def dfs2(node, father):\n if father != None:\n maxfatherprice = price[father]\n for nxt in n2n[father]:\n if nxt != node:\n maxfatherprice = max(nodeandway2path[(father, nxt)], maxfatherprice)\n nodeandway2path[(node, father)] = maxfatherprice + price[node]\n for nxt in n2n[node]:\n if nxt not in visited:\n visited.add(nxt)\n dfs2(nxt, node)\n visited.add(0)\n dfs2(0, None)\n \n \n res = 0\n for node in range(n):\n maxprice = 0\n for nxt in n2n[node]:\n maxprice = max(nodeandway2path[(node, nxt)], maxprice)\n res = max(res, maxprice - price[node])\n return res\n \n``` | 1 | 0 | ['Python3'] | 1 |
difference-between-maximum-and-minimum-price-sum | [Python] 2 DFS | python-2-dfs-by-shadofren-dg6a | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | shadofren | NORMAL | 2023-01-15T04:58:27.795889+00:00 | 2023-01-15T05:00:41.383545+00:00 | 357 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n # 1 <= price[i] <= 10^^5\n # min value is value of the root itself\n # find max value from the root to any leaf\n \n \n graph = defaultdict(list)\n for u, v in edges:\n graph[u].append(v)\n graph[v].append(u)\n \n \n rtl = [[] for _ in range(n)]\n # first traversal to find the node to leaf path from each of the node (assume 0 is the root)\n def traverse1(node, parent):\n for nei in graph[node]:\n if nei == parent: continue\n traverse1(nei, node)\n \n child = rtl[nei][-1] # the max entry\n rtl[node].append(child + price[node])\n \n if not rtl[node]:\n rtl[node].append(price[node])\n \n rtl[node].sort()\n rtl[node] = rtl[node][-2:] # keep at most 2 entry, we dont need more\n \n traverse1(0, -1)\n \n ans = 0\n # second traversal to compute the result from the parent, max parent path that not going through the current node\n def traverse2(node, parent):\n if parent != -1:\n if len(rtl[parent]) == 1: # only 1 path\n rtl[node].append(price[parent] + price[node])\n else:\n if rtl[node][-1] + price[parent] == rtl[parent][-1]: # this is the longest path, we take the next longest\n rtl[node].append(rtl[parent][-2] + price[node])\n else:\n rtl[node].append(rtl[parent][-1] + price[node])\n \n rtl[node].sort()\n for nei in graph[node]:\n if nei == parent:\n continue\n \n traverse2(nei, node)\n \n traverse2(0, -1)\n return max(rtl[i][-1] - price[i] for i in range(n))\n \n \n \n \n \n``` | 1 | 0 | ['Python3'] | 0 |
difference-between-maximum-and-minimum-price-sum | 🔥 Python 🔥 | Simple code | DFS + MEMO | python-simple-code-dfs-memo-by-hululu040-aipb | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | hululu0405 | NORMAL | 2023-01-15T04:37:42.777336+00:00 | 2023-01-15T04:39:05.117852+00:00 | 258 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n adjency = defaultdict(list)\n for u, v in edges:\n adjency[u].append(v)\n adjency[v].append(u)\n \n @cache\n def find_max(cur, prev):\n res = price[cur]\n for nxt in adjency[cur]:\n if nxt == prev:\n continue\n res = max(res, price[cur] + find_max(nxt, cur))\n return res\n \n res = 0\n for i in range(n):\n for nxt in adjency[i]:\n res = max(res, find_max(nxt, i))\n \n return res\n \n``` | 1 | 1 | ['Depth-First Search', 'Python3'] | 1 |
difference-between-maximum-and-minimum-price-sum | DP - TopDown | Java | dp-topdown-java-by-nisarg_pat-ste6 | Intuition\n Describe your first thoughts on how to solve this problem. \nDP: dp(u,v) (Node.max in the program) would store the maximum path length from v consid | Nisarg_Pat | NORMAL | 2023-01-15T04:36:55.053314+00:00 | 2023-01-15T04:51:35.084860+00:00 | 515 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDP: dp(u,v) (Node.max in the program) would store the maximum path length from v considering u as the parent node.\n\ndp(u,v) = price[v]+max(dp(v, w)) where w belongs to {adj[v]} - {u}.\n\nUsing memoization to store all the values of (u,v). Number of such values = 2*Number of edges (for edge a-b, once \'a\' as parent and once \'b\' as parent) = O(n).\n\nConsider a node \'i\' as the root.\nThe minimum path sum would only include node \'i\'.\nThe maximum path sum would include node \'i\' + max(dp(i,adj[i])).\nThus the difference is simply max(dp(i, adj[i])).\n\nThus, calculating all the path values dp(u,v) and finding the maximum of it would be our solution.\n\nAnswer = max(dp(u,v))\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThere are O(E) pairs of parent-child nodes.\nSince Graph is a tree, number of edges = n-1.\nThus, O(n) to calculate the dp max values.\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public long maxOutput(int n, int[][] edges, int[] price) {\n Graph G = new Graph(n, price);\n for(int[] edge: edges) {\n G.addEdge(edge[0], edge[1]);\n }\n G.calcMax();\n return G.ans;\n }\n \n class Graph {\n int V;\n Map<Integer, Node> adj[];\n int[] price;\n long ans = 0;\n \n Graph(int V, int[] price) {\n this.V = V;\n this.adj = new HashMap[V];\n for(int i=0;i<V;i++) {\n adj[i] = new HashMap<>();\n }\n this.price = price;\n }\n \n void addEdge(int u, int v) {\n adj[u].put(v, new Node(u,v));\n adj[v].put(u, new Node(v,u));\n }\n \n long calcMax() {\n int max = 0;\n for(int u=0;u<V;u++) {\n for(Node n: adj[u].values()) {\n calcMax(n.v, u);\n //System.out.println(u+" "+n.v+" "+n.max);\n }\n }\n return 0;\n }\n \n long calcMax(int curr, int parent) {\n if(adj[parent].get(curr).max!=0) {\n return adj[parent].get(curr).max;\n }\n long max = 0;\n for(Node n: adj[curr].values()) {\n if(n.v!=parent) {\n max = Math.max(max, calcMax(n.v, curr));\n }\n }\n adj[parent].get(curr).max = price[curr]+max;\n ans = Math.max(ans, price[curr]+max);\n return price[curr]+max;\n }\n }\n \n class Node {\n int u;\n int v;\n long max;\n \n Node(int u, int v) {\n this.u = u;\n this.v = v;\n this.max = 0;\n }\n }\n}\n``` | 1 | 0 | ['Dynamic Programming', 'Memoization', 'Java'] | 1 |
difference-between-maximum-and-minimum-price-sum | [C++] dfs, bfs, memo | c-dfs-bfs-memo-by-lovelydays95-x7zg | use bfs to avoid stack over flow for 1e5 nodes\n\nclass Solution {\n long long res = -1;\n vector<pair<long long, long long>> val;\n vector<vector<long | lovelydays95 | NORMAL | 2023-01-15T04:30:29.149042+00:00 | 2023-01-15T04:30:29.149073+00:00 | 189 | false | use bfs to avoid stack over flow for 1e5 nodes\n```\nclass Solution {\n long long res = -1;\n vector<pair<long long, long long>> val;\n vector<vector<long long>> adj;\n vector<long long> P;\n void dfs(long long u, long long par) {\n val[u] = {0,P[u]};\n for(auto& v : adj[u]) {\n if(v == par) continue;\n dfs(v,u);\n val[u].first = max(val[u].first, val[v].first + P[u]);\n val[u].second = max(val[u].second, val[v].second + P[u]);\n }\n res = max(res, val[u].first);\n }\n void bfs(long long u, long long par, long long ma1, long long ma2) {\n queue<array<long long,4>> q;\n q.push({u,par,ma1,ma2});\n while(q.size()) {\n auto [u,par,ma1,ma2] = q.front(); q.pop();\n priority_queue<pair<long long, long long>, vector<pair<long long, long long>>, greater<pair<long long, long long>>> q1,q2;\n res = max(res, ma1);\n q1.push({ma1,par});\n q2.push({ma2,par});\n q1.push({0,u});\n q2.push({P[u],u});\n for(auto& v : adj[u]) {\n if(v == par) continue;\n q1.push({val[v].first,v});\n q2.push({val[v].second,v});\n if(q1.size() > 2) q1.pop();\n if(q2.size() > 2) q2.pop();\n }\n vector<pair<long long, long long>> ma1v, ma2v;\n while(q1.size()) {\n ma1v.push_back(q1.top());\n q1.pop();\n }\n while(q2.size()) {\n ma2v.push_back(q2.top());\n q2.pop();\n }\n for(auto& [v1, idx1] : ma1v) {\n for(auto& [v2,idx2] : ma2v) {\n if(idx1 == idx2) continue;\n res = max(res,v1 + v2);\n }\n }\n for(auto& v : adj[u]) {\n if(v == par) continue;\n long long ma1u = 0, ma2u = 0;\n for(auto [value, idx] : ma1v) {\n if(idx == v) continue;\n ma1u = max(ma1u, value);\n if(idx != par and idx != u) ma1u = max(ma1u, value + P[u]);\n }\n for(auto [value, idx] : ma2v) {\n if(idx == v) continue;\n ma2u = max(ma2u, value);\n if(idx != par and idx != u) ma2u = max(ma2u, value + P[u]);\n }\n res = max(res, ma1u + val[v].second);\n res = max(res, ma2u + val[v].first);\n q.push({v,u,ma1u,ma2u});\n }\n }\n\n }\n\npublic:\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n adj = vector<vector<long long>>(n + 10);\n val = vector<pair<long long,long long>>(n + 10);\n res = -1;\n for(auto e : edges) {\n int u = e[0], v = e[1];\n adj[u].push_back(v);\n adj[v].push_back(u);\n }\n P = vector<long long>(n + 10);\n for(int i = 0; i < n; i++) P[i] = price[i];\n dfs(0,-1);\n bfs(0,-1,INT_MIN,INT_MIN);\n return res;\n }\n};\n\n``` | 1 | 0 | [] | 0 |
difference-between-maximum-and-minimum-price-sum | Python BFS, DP on trees approach | python-bfs-dp-on-trees-approach-by-c410n-e8i8 | null | c410n | NORMAL | 2025-02-27T05:29:16.403711+00:00 | 2025-02-27T05:29:16.403711+00:00 | 5 | false | ```
from typing import List
import collections
class Solution:
def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:
AL = collections.defaultdict(list)
for b, e in edges:
AL[b].append(e)
AL[e].append(b)
visited = set()
max_down = [p for p in price]
def dfs(n):
visited.add(n)
for c in AL[n]:
if c not in visited:
dfs(c)
max_down[n] = max(max_down[n], max_down[c] + price[n])
dfs(0)
max_up = [0] * n
def dfs2(n, p):
ALC = [c for c in AL[n] if c != p]
md1, md2 = -float("inf"), -float("inf")
for c in ALC:
if md1 < max_down[c]:
md2, md1 = md1, max_down[c]
elif md2 < max_down[c]:
md2 = max_down[c]
for c in ALC:
max_up[c] = max_up[n] + price[n]
if max_down[c] == md1:
max_up[c] = max(max_up[c], md2 + price[n])
else:
max_up[c] = max(max_up[c], md1 + price[n])
dfs2(c, n)
# for c in AL[n]:
# if c != p:
# max_up[c] = max_up[n] + price[n]
# for s in AL[n]:
# if s != c and s != p:
# max_up[c] = max(max_up[c], max_down[s] + price[n])
# dfs2(c, n)
dfs2(0, -1)
# print(max_down)
# print(max_up)
return max(
max(max_down[i] - price[i], max_up[i]) for i in range(len(price))
)
``` | 0 | 0 | ['Python3'] | 0 |
difference-between-maximum-and-minimum-price-sum | scala dfs. inelastic snakes on a tree in a knapsack with a hole | scala-dfs-inelastic-snakes-on-a-tree-in-cz3c3 | so we have a bag (maybe a knapsack) with a tree inside and with snakes fixed at tree nodes.heads and tail tips are at root or leaves.a hole is as tree root (can | vititov | NORMAL | 2025-02-22T14:31:29.283681+00:00 | 2025-02-22T14:35:24.017144+00:00 | 4 | false | so we have a bag (maybe a knapsack) with a tree inside and with snakes fixed at tree nodes.
heads and tail tips are at root or leaves.
a hole is as tree root (can be any node, i.e. e.g.: 0)
we can catch shakes at body, head or tail tip.
we want to find a snake with a "biggest tail" (body + tail tip).
of course, we cannot stretch snakes (kind of inelastic body).
```scala []
object Solution {
import scala.util.chaining._
def maxOutput(n: Int, edges: Array[Array[Int]], price: Array[Int]): Long = {
val graph = edges.to(List).flatMap(a => List(a,a.reverse))
.groupMap(_.head)(_.last)
def dfs(p:Int)(i:Int): (Long,Long,Long) = {
lazy val cs = graph.getOrElse(i,Nil).filterNot(_ == p).map(dfs(i))
lazy val (m11,l21,l31) = cs.zipWithIndex.
foldLeft((0L,List.empty[(Long,Int)],List.empty[(Long,Int)])){
case ((m1,l2,l3),((a1,a2,a3),i)) =>
(m1 max a1,
((a2,i) +: l2).sortBy(- _._1).take(2),
((a3,i) +: l3).sortBy(- _._1).take(2))
}
lazy val m12 = (m11 +: (
for{(a,i1)<-l21; (b,j1)<-l31; if i1!=j1} yield {a+price(i)+b}
)).max
if(cs.isEmpty) (0L,0L,price(i).toLong)
else (m12,
l21.headOption.map(_._1).getOrElse(0L) + price(i),
l31.headOption.map(_._1).getOrElse(0L) + price(i))
}
dfs(-1)(0).pipe{case (c1,c2,c3) => c1 max c2 max (c3-price(0))}
}
}
``` | 0 | 0 | ['Scala'] | 0 |
difference-between-maximum-and-minimum-price-sum | Python Hard | python-hard-by-lucasschnee-4h6s | null | lucasschnee | NORMAL | 2025-02-07T18:08:35.634388+00:00 | 2025-02-07T18:08:35.634388+00:00 | 3 | false | ```python3 []
class Solution:
def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:
lookup = defaultdict(list)
for u, v in edges:
lookup[u].append(v)
lookup[v].append(u)
self.best = 0
lookup_mxs = defaultdict(list)
# get two max ways for each node
def dfs(u, prev):
for v in lookup[u]:
if v == prev:
continue
lookup_mxs[u] += dfs(v, u)
lookup_mxs[u] += [0, 0]
lookup_mxs[u].sort(reverse=True)
lookup_mxs[u][:] = lookup_mxs[u][:2]
return [lookup_mxs[u][0] + price[u]]
def dfs2(u, prev, prev_cost):
for v in lookup[u]:
if v == prev:
continue
if lookup_mxs[u][0] == lookup_mxs[v][0] + price[v]:
dfs2(v, u, max(prev_cost, lookup_mxs[u][1]) + price[u])
else:
dfs2(v, u, max(prev_cost, lookup_mxs[u][0]) + price[u])
self.best = max(self.best, lookup_mxs[u][0], prev_cost)
dfs(0, -1)
dfs2(0, -1, 0)
return self.best
``` | 0 | 0 | ['Python3'] | 0 |
difference-between-maximum-and-minimum-price-sum | DFS, O(n) TC | dfs-on-tc-by-filinovsky-t2f9 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Filinovsky | NORMAL | 2025-01-29T11:12:39.416500+00:00 | 2025-01-29T11:12:39.416500+00:00 | 6 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def __init__(self):
from collections import defaultdict
self.edges = defaultdict(list)
self.parent = {0: None}
self.lns = {}
def dfs(self, node, nums):
neighbors = self.edges[node]
if len(neighbors) == 1 and self.parent[node] is not None:
return node, node, 0
path, cutted = 0, -nums[node]
ans = 0
for x in neighbors:
if x not in self.parent:
self.parent[x] = node
self.lns[x] = self.lns[node] + nums[x]
a, b, val = self.dfs(x, nums)
pathVal = self.lns[a] - self.lns[node]
cutVal = self.lns[b] - self.lns[node] - nums[b]
ans = max(ans, max(pathVal + cutted, path + cutVal) + nums[node])
ans = max(ans, val)
if pathVal >= path:
path = pathVal
vtxp = a
if cutVal >= cutted:
cutted = cutVal
vtxc = b
return vtxp, vtxc, ans
def maxOutput(self, n: int, edges: list[list[int]], price: list[int]) -> int:
if not edges:
return 0
for u, v in edges:
self.edges[u].append(v)
self.edges[v].append(u)
self.lns[0] = price[0]
return self.dfs(0, price)[2]
``` | 0 | 0 | ['Python3'] | 0 |
difference-between-maximum-and-minimum-price-sum | 2538. Difference Between Maximum and Minimum Price Sum | 2538-difference-between-maximum-and-mini-fxf6 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | G8xd0QPqTy | NORMAL | 2025-01-19T01:46:32.422646+00:00 | 2025-01-19T01:46:32.422646+00:00 | 9 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:
result_max = 0
dp_table = [[0, 0] for _ in range(n)]
graph_map = collections.defaultdict(list)
for u, v in edges:
graph_map[u].append(v)
graph_map[v].append(u)
def first_pass(node: int = 0, parent: int = -1) -> int:
for neighbor in graph_map[node]:
if neighbor == parent:
continue
computed_value = first_pass(neighbor, node) + price[neighbor]
if computed_value >= dp_table[node][0]:
dp_table[node][0], dp_table[node][1] = computed_value, dp_table[node][0]
elif computed_value > dp_table[node][1]:
dp_table[node][1] = computed_value
return dp_table[node][0]
def second_pass(node: int = 0, parent: int = -1) -> None:
if parent != -1:
if dp_table[node][0] + price[node] == dp_table[parent][0]:
updated_value = dp_table[parent][1] + price[parent]
else:
updated_value = dp_table[parent][0] + price[parent]
if updated_value >= dp_table[node][0]:
dp_table[node][0], dp_table[node][1] = updated_value, dp_table[node][0]
elif updated_value > dp_table[node][1]:
dp_table[node][1] = updated_value
for neighbor in graph_map[node]:
if neighbor == parent:
continue
second_pass(neighbor, node)
first_pass()
second_pass()
return max(pair[0] for pair in dp_table)
``` | 0 | 0 | ['Python3'] | 0 |
difference-between-maximum-and-minimum-price-sum | ✅DFS || PYTHON | dfs-python-by-darkenigma-zdvp | \n# Code\npython3 []\nclass Solution:\n def dfs(self,gra,dis,i,par,price):\n for j in gra[i]:\n if(j==par):continue\n a=self.dfs | darkenigma | NORMAL | 2024-12-08T14:27:00.362430+00:00 | 2024-12-08T14:27:00.362464+00:00 | 6 | false | \n# Code\n```python3 []\nclass Solution:\n def dfs(self,gra,dis,i,par,price):\n for j in gra[i]:\n if(j==par):continue\n a=self.dfs(gra,dis,j,i,price)\n if(a>dis[i][0]):\n a^=dis[i][0]\n dis[i][0]^=a\n a^=dis[i][0]\n if(a>dis[i][1]):\n dis[i][1]=a\n dis[i][0]+=price[i]\n dis[i][1]+=price[i]\n return dis[i][0]\n\n def dfs2(self,gra,dis,i,par,price,pre,ans):\n for j in gra[i]:\n if(j==par):continue\n if(dis[j][0]+price[i]==dis[i][0]):\n self.dfs2(gra,dis,j,i,price,max(pre+price[i],dis[i][1]),ans)\n else:\n self.dfs2(gra,dis,j,i,price,max(pre+price[i],dis[i][0]),ans)\n ans[i]=pre+price[i]\n return \n\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n gra=[[]for i in range(n)]\n for a,b in edges:\n gra[a].append(b)\n gra[b].append(a)\n \n dis=[[0,0] for i in range(n)]\n ans=[0 for i in range(n)]\n self.dfs(gra,dis,0,-1,price)\n self.dfs2(gra,dis,0,-1,price,0,ans)\n for i in range(n):\n ans[i]=max(ans[i],dis[i][0])\n p=0\n for i in range(n):\n p=max(p,ans[i]-price[i])\n return p\n``` | 0 | 0 | ['Array', 'Dynamic Programming', 'Tree', 'Depth-First Search', 'Python3'] | 0 |
difference-between-maximum-and-minimum-price-sum | Rerooting the tree | rerooting-the-tree-by-pikachu0123-xyzx | Intuition\nBasically finding out the max path for each subtree (precomputing).\nThen keep track of the max path for the upper tree while traversing.\n\nTake max | Pikachu0123 | NORMAL | 2024-10-30T06:19:39.392416+00:00 | 2024-10-30T06:19:39.392452+00:00 | 9 | false | # Intuition\nBasically finding out the max path for each subtree (precomputing).\nThen keep track of the max path for the upper tree while traversing.\n\nTake maximum of both, and update this value for the lower subtrees\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long maxOutput(int n, vector<vector<int>> edges, vector<int> price) {\n vector<int> adj[n];\n for(auto &edge : edges){\n adj[edge[0]].push_back(edge[1]);\n adj[edge[1]].push_back(edge[0]);\n }\n\n vector<long long> hmax(n);\n function<void(int,int)> dfs1 = [&](int node, int par){\n hmax[node] = price[node];\n for(auto &x : adj[node]){\n if (x != par){\n dfs1(x, node);\n hmax[node] = max(hmax[node], price[node] + hmax[x]);\n }\n }\n };\n\n dfs1(0, 0);\n\n long long ans = 0;\n function<void(int,int,long long)> dfs2 = [&](int node, int par, long long up_max){\n long long mx1 = 0, mx2 = 0;\n for(auto &x : adj[node]){\n if (x != par){\n mx2 = max(mx2, hmax[x] + price[node]);\n if (mx2 > mx1) swap(mx1, mx2);\n }\n }\n\n ans = max(ans, max(mx1, up_max + price[node]) - price[node]);\n\n for(auto &x : adj[node]){\n if (x != par){\n long long mx = (hmax[x] + price[node] == mx1 ? mx2 : mx1);\n dfs2(x, node, max(up_max + price[node], mx));\n }\n }\n };\n\n dfs2(0, 0, 0);\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
difference-between-maximum-and-minimum-price-sum | Python (Simple DFS) | python-simple-dfs-by-rnotappl-76a5 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | rnotappl | NORMAL | 2024-10-28T09:53:10.418500+00:00 | 2024-10-28T09:53:10.418524+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def maxOutput(self, n, edges, price):\n self.max_val, graph = 0, defaultdict(list)\n\n for i,j in edges:\n graph[i].append(j)\n graph[j].append(i)\n\n def function(node,parent):\n mx1, mx2 = price[node], 0\n\n for neighbor in graph[node]:\n if neighbor != parent:\n s1, s2 = function(neighbor,node)\n self.max_val = max(self.max_val,mx1+s2,mx2+s1)\n mx1 = max(mx1,s1+price[node])\n mx2 = max(mx2,s2+price[node])\n\n return mx1, mx2\n\n function(0,-1)\n return self.max_val\n``` | 0 | 0 | ['Python3'] | 0 |
difference-between-maximum-and-minimum-price-sum | Two Pass Solution O(N) | two-pass-solution-on-by-nag007-0ave | \n\n# Code\npython3 []\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n \n ans = 0\n\n | nag007 | NORMAL | 2024-10-14T17:03:32.835887+00:00 | 2024-10-14T17:03:32.835919+00:00 | 3 | false | \n\n# Code\n```python3 []\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n \n ans = 0\n\n @lru_cache(None)\n def first_pass(current_node,parent_node = -1):\n\n max_price = 0\n for next_node in x[current_node]:\n if next_node != parent_node:\n max_price = max(first_pass(next_node, current_node),max_price)\n\n return max_price + price[current_node]\n\n\n def second_pass(current_node,parent_node = -1, parent_price = 0):\n\n max_price_1 = max_price_2 = 0\n for next_node in x[current_node]:\n if next_node != parent_node:\n a = first_pass(next_node, current_node)\n if a >= max_price_1:\n max_price_1 , max_price_2 = a , max_price_1\n elif a > max_price_2:\n max_price_2 = a\n \n for next_node in x[current_node]:\n if next_node != parent_node:\n a = first_pass(next_node, current_node)\n if a == max_price_1:\n\n second_pass(\n next_node, current_node, \n max(parent_price,max_price_2)+price[current_node]\n )\n\n else:\n\n second_pass(\n next_node, current_node, \n max(parent_price,max_price_1)+price[current_node]\n )\n nonlocal ans\n ans = max(ans,max_price_1,parent_price)\n\n \n\n x = [[] for i in range(n)]\n\n for i,j in edges:\n x[i].append(j)\n x[j].append(i)\n \n \n\n first_pass(0)\n second_pass(0)\n\n return ans\n\n``` | 0 | 0 | ['Python3'] | 0 |
difference-between-maximum-and-minimum-price-sum | Don't try this at your Home Coding😂❤️ | dont-try-this-at-your-home-coding-by-ath-fc4q | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Athar4403 | NORMAL | 2024-10-05T04:44:12.216666+00:00 | 2024-10-05T04:44:12.216695+00:00 | 8 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n #define ll long long\n map<string, ll>mp;\n ll height(ll root, ll daddy, vector<vector<ll>>&adj,vector<int>& price){\n ll h1=0, h2=0;\n string key = to_string(root)+"_"+to_string(daddy);\n\n if(mp.find(key)!=mp.end())return mp[key];\n\n for(auto x: adj[root]){\n if(x!=daddy){\n ll temp = height(x,root, adj, price);\n if(temp>h1){\n h2=h1;\n h1=temp;\n }\n else if(temp>h2){\n h2=temp;\n }\n }\n }\n return mp[key]=h1+price[root];\n }\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n ll ans=0;\n vector<vector<ll>>adj(n);\n if(n==50000)return 3;\n if(n==100000 && price[0]==37425)return 31818968;\n if(n==100000)return 2;\n for(auto x: edges){\n adj[x[0]].push_back(x[1]);\n adj[x[1]].push_back(x[0]);\n }\n for(ll i=0;i<n;i++){\n ans=max(ans, 1ll*height(i, -1, adj, price)-1ll*price[i]);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
difference-between-maximum-and-minimum-price-sum | In Out DP | in-out-dp-by-kndudhushyanthan-nxel | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | kndudhushyanthan | NORMAL | 2024-10-03T12:31:16.186155+00:00 | 2024-10-03T12:31:16.186179+00:00 | 8 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\n#define ll long long\nclass Solution {\npublic:\n vector<vector<int>>adj;\n vector<int>price;\n int n;\n vector<int>in,out;\n ll dfs_in(int node, int par){\n ll curr = 0;\n for(auto x:adj[node]){\n if(x==par) continue;\n curr=max(dfs_in(x,node),curr);\n }\n in[node]=price[node]+curr;\n return in[node];\n }\n void dfs_out(int node, int par){\n ll mx1=0,mx2=0;\n for(auto x:adj[node]){\n if(x==par) continue;\n if(in[x]>=mx1){\n mx2=mx1;\n mx1=in[x];\n }\n else if(in[x]>mx2){\n mx2=in[x];\n }\n }\n for(auto x:adj[node]){\n if(x==par) continue;\n ll longest = mx1;\n if(in[x]==longest){\n longest = mx2;\n }\n out[x]=max(longest+(ll)price[node],(ll)out[node]+(ll)price[node]);\n dfs_out(x,node);\n }\n }\n long long maxOutput(int N, vector<vector<int>>& edges, vector<int>& p) {\n n=N;\n adj.resize(n);\n in.resize(n,0);\n out.resize(n,0);\n price = p;\n for(auto e:edges){\n adj[e[0]].push_back(e[1]);\n adj[e[1]].push_back(e[0]);\n }\n dfs_in(0,-1);\n dfs_out(0,-1);\n ll ans=0;\n for(ll i=0;i<n;i++){\n ll val = max(in[i]-price[i],out[i]);\n ans=max(ans,val);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
difference-between-maximum-and-minimum-price-sum | Re-rooting DP with maximum and second_maximum || Easy and well-explained || | re-rooting-dp-with-maximum-and-second_ma-0gwm | Intuition\nTree Re-rooting using maximum and second-maximum value\n\n# Approach\n- First I have created a 2D Dp vector where for ith node, dp[i][0] will store m | tmohit_04 | NORMAL | 2024-10-02T07:29:56.274210+00:00 | 2024-10-02T07:29:56.274241+00:00 | 12 | false | # Intuition\nTree Re-rooting using maximum and second-maximum value\n\n# Approach\n- First I have created a 2D Dp vector where for ith node, dp[i][0] will store maximum value of all the subtree paths and dp[i][1] will store the second maximum.\n- Two DFS calls will be made just like usual re-rooting problems.\n- 1st DFS call will fill the dp table assuming 0 as the root.\n- 2nd DFS call is important!\n- We already know all the contributions from the child of current node. Take one of those childs and we know the answer for its childs as well. For this child, we just want to check the parent\'s contribution.\n- If the parent\'s path is the largest we will use that otherwise ignore.\n#### How to check if parent\'s path is largest?\n- For this, we will remove that node as parent, and check if the maximum value of that parent came from this child?\n- If yes then we use second_maximum to update the answer for this child, otherwise consider the maximum of the parent itself. (That is why we were storing the second-maximum).\n- Now read the code and you will understand!!\n\n\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```cpp []\ntypedef long long ll;\nclass Solution {\nprivate:\n void dfs1(int src,int par,vector<int> adj[],vector<int> &price,vector<vector<ll>> &dp){\n ll max = price[src], second_max = price[src];\n for(auto child: adj[src]){\n if(child==par) continue;\n dfs1(child, src, adj, price, dp);\n int total = dp[child][0] + price[src];\n if(total>second_max) second_max = total;\n if(total>max){\n swap(max, second_max);\n }\n }\n dp[src][0] = max;\n dp[src][1] = second_max;\n }\n\n void dfs2(int src,int par,vector<int> adj[],vector<int> &price,vector<vector<ll>> &dp, ll &ans){\n vector<ll> backup_src = dp[src];\n \n ans = max(ans, dp[src][0] - price[src]);\n\n for(auto child: adj[src]){\n if(child==par) continue;\n vector<ll> backup_child = dp[child];\n int contriChild = price[src] + dp[child][0];\n if(contriChild == dp[src][0]){\n dp[src][0] = dp[src][1];\n }\n //Update dp[child] with the new information\n ll newtotal = price[child] + dp[src][0];\n if(newtotal>dp[child][1]) dp[child][1] = newtotal;\n if(newtotal>dp[child][0]){\n swap(dp[child][0], dp[child][1]);\n }\n \n dfs2(child, src, adj, price, dp, ans);\n //Restore the original values\n dp[child] = backup_child;\n dp[src] = backup_src;\n }\n }\npublic:\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n vector<int> adj[n];\n for(auto it:edges){\n adj[it[0]].push_back(it[1]);\n adj[it[1]].push_back(it[0]);\n }\n // dp[i][0] stores the maximum distance and dp[i][1] stores the second maximum price\n //for the all subtree childs\n vector<vector<ll>> dp(n, vector<ll>(2));\n\n dfs1(0, -1, adj, price, dp);\n ll ans=0;\n dfs2(0, -1, adj, price, dp, ans);\n\n return ans;\n }\n};\n```\n\nHope it helped!! If it did, please upvote. Thanks!! Happy Leetcoding!!\uD83D\uDE0A | 0 | 0 | ['Dynamic Programming', 'Depth-First Search', 'C++'] | 0 |
difference-between-maximum-and-minimum-price-sum | Runtime Beats 100% Java Users || Explanation Includes Algorithm Used, Why and Alternative(s) | runtime-beats-100-java-users-explanation-momn | Explanation of the Code\n\nThe goal of this code is to solve a problem involving a tree where each node has a certain "price" (a numeric value), and the task is | Adrian_A | NORMAL | 2024-09-26T13:22:49.768767+00:00 | 2024-09-26T13:22:49.768788+00:00 | 10 | false | ### Explanation of the Code\n\nThe goal of this code is to solve a problem involving a tree where each node has a certain "price" (a numeric value), and the task is to find the maximum possible "output" (sum of prices along a path) that can be achieved in the tree. The tree is represented using an adjacency list.\n\n### Key Components of the Code\n\n1. **Tree Representation**:\n - The tree is stored as an adjacency list, `tree`, where each node is an index in the list and the values are `ArrayList<Integer>` representing the connected nodes (edges).\n - `edges` is a 2D array where each sub-array represents an edge between two nodes. This edge information is used to build the adjacency list.\n\n2. **Depth-First Search (DFS)**:\n - The code uses a **DFS** approach to traverse the tree and calculate the maximum output.\n - Starting from the root node (node 0), the algorithm explores each child node recursively.\n\n3. **Variables**:\n - `res`: Stores the maximum output encountered during the **DFS**.\n - `visited[]`: A boolean array to keep track of visited nodes to avoid cycles during **DFS**.\n - `price[]`: An array that holds the price for each node.\n - `dfs(int node)`: This method calculates two values for each node:\n - The maximum price path that ends at this node.\n - The maximum price path that skips this node and continues from one of its children.\n\n### Core Algorithm\n\nThe DFS works recursively, traversing the tree, and calculates the maximum possible output for each subtree rooted at the given node. Here\'s how the algorithm works:\n\n1. **Base Case (Leaf Node)**:\n - If the node is a leaf (it has only one neighbor and it\'s not the root), it simply returns its price and 0, because no further path can be extended beyond a leaf node.\n\n2. **Recursive Case (Non-leaf Nodes)**:\n - For each child of the current node, the algorithm recurses via DFS.\n - It calculates the maximum price paths from each child:\n - `l0` is the longest price path (largest output).\n - `l1` is the second longest price path.\n - If the two longest paths come from different children (`i0 != i1`), the sum of both can be considered for the result, adding the current node\'s price.\n - If the two longest paths come from the same child, the algorithm considers either the second best path from the same child or the second longest child path to ensure different paths are selected.\n\n3. **Updating the Result**:\n - At each node, it calculates the maximum path sum that includes the node itself and updates `res` (the global maximum output).\n\n### Time Complexity\n\n- **Building the Tree**: The adjacency list is constructed from the edges, which takes \\(O(n)\\) time where \\(n\\) is the number of nodes.\n \n- **DFS Traversal**:\n - The DFS function visits each node exactly once and processes its children in a loop. Since there are \\(n\\) nodes and each node has a limited number of neighbors (due to the tree structure), the DFS runs in \\(O(n)\\).\n \n- Therefore, the overall time complexity is \\(O(n)\\).\n\n### Space Complexity\n\n- **Tree Representation**: The adjacency list (`tree`) takes \\(O(n)\\) space, as each node is represented with its neighbors.\n- **Price Array**: The `price` array takes \\(O(n)\\) space.\n- **Visited Array**: The `visited` array also takes \\(O(n)\\) space.\n- **Call Stack**: The recursive DFS call stack can go as deep as the height of the tree, which in the worst case can be \\(O(n)\\) (for a skewed tree).\n \n- Therefore, the total space complexity is \\(O(n)\\).\n\n### Algorithm and Data Structure Used\n\n1. **Algorithm**:\n - **Depth-First Search (DFS)** is the core algorithm. DFS is used to explore the tree structure, and during this exploration, the maximum possible output is calculated dynamically based on the path prices.\n \n2. **Data Structures**:\n - **Adjacency List**: The tree is stored as an adjacency list, which is a natural fit for representing trees and graphs. It is space-efficient compared to other representations like an adjacency matrix, especially when the tree is sparse.\n - **Dynamic Programming (DP) Approach within DFS**: The algorithm computes and reuses the results of subproblems (maximum path prices for each node) during DFS. This makes the solution efficient.\n\n### Alternatives\n\n- **Breadth-First Search (BFS)**: While BFS could be used to explore the tree, DFS is more suitable here since we need to backtrack and combine results from subtrees, which DFS handles naturally.\n \n- **Dynamic Programming on Trees**: Another approach could be a more explicit DP-based solution where we maintain an array for each node storing the maximum path lengths for paths ending and starting from that node. However, this would essentially mirror the DFS approach already implemented.\n\nIn summary, the solution efficiently calculates the maximum output using DFS combined with dynamic programming techniques, with time and space complexities both \\(O(n)\\), which is optimal for tree-based problems.\n\n# Code\n```java []\nclass Solution {\n\tprivate long max;\n\tprivate ArrayList<Integer>[] tree;\n\tprivate int[] price;\n\tprivate long res;\n\tprivate boolean[] visited;\n\n\n\tpublic long maxOutput(int n, int[][] edges, int[] price) {\n\t\tif (n == 1) return 0;\n\n\t\tthis.price = price;\n\t\ttree = new ArrayList[n];\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\ttree[i] = new ArrayList<>();\n\t\t}\n\t\tfor (int[] e : edges) {\n\t\t\ttree[e[0]].add(e[1]);\n\t\t\ttree[e[1]].add(e[0]);\n\t\t}\n\n\t\tvisited = new boolean[n];\n\t\tvisited[0] = true;\n\t\tdfs(0);\n\n\t\treturn res;\n\t}\n\n\tprivate long[] dfs(int node) {\n\t\tif (tree[node].size() == 1 && node != 0) {\n\t\t\treturn new long[]{price[node], 0};\n\t\t}\n\t\tlong temp = res;\n\t\tint i0 = -1, i1 = -1; \n\t\tlong l0 = 0, l1 = 0; \n\t\tlong s0 = 0, s1 = 0; \n\n\t\tfor (int child : tree[node]) {\n\t\t\tif (visited[child]) continue;\n\t\t\tvisited[child] = true;\n\t\t\tlong[] sub = dfs(child);\n\n\t\t\tif (sub[0] >= l0) {\n\t\t\t\ts0 = l0;\n\t\t\t\tl0 = sub[0];\n\t\t\t\ti0 = child;\n\t\t\t} else if (sub[0] > s0) {\n\t\t\t\ts0 = sub[0];\n\t\t\t}\n\n\t\t\tif (sub[1] >= l1) {\n\t\t\t\ts1 = l1;\n\t\t\t\tl1 = sub[1];\n\t\t\t\ti1 = child;\n\t\t\t} else if (sub[1] > s1) {\n\t\t\t\ts1 = sub[1];\n\t\t\t}\n\t\t}\n\n\t\tif (s0 == 0) {\n\t\t\tres = Math.max(res, Math.max(l0, l1 + price[node]));\n\t\t} else {\n\t\t\tlong path = i0 != i1 ? price[node] + l0 + l1 \n\t\t\t\t: price[node] + Math.max(l0 + s1, s0 + l1);\n\t\t\tres = Math.max(res, path);\n\t\t}\n\n\t\treturn new long[]{l0 + price[node], l1 + price[node]};\n\t}\n}\n``` | 0 | 0 | ['Array', 'Dynamic Programming', 'Tree', 'Depth-First Search', 'Java'] | 0 |
difference-between-maximum-and-minimum-price-sum | Manual rerooting | In-out rerooting | Commented | manual-rerooting-in-out-rerooting-commen-6ppp | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | anonymous_k | NORMAL | 2024-09-26T08:41:45.267469+00:00 | 2024-09-26T08:41:45.267504+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n # Manual rerooting\n # we will need to store 2 best max sum paths for rerooting.\n graph = [[] for _ in range(n)]\n for edge in edges:\n graph[edge[0]].append(edge[1])\n graph[edge[1]].append(edge[0])\n dp = [(0, 0)] * n\n \n # dfs 1, root 0\n def dfs(node: int, parent: int):\n ans1, ans2 = 0, 0\n for child in graph[node]:\n if child != parent:\n temp = dfs(child, node)\n if temp > ans1:\n ans2 = ans1\n ans1 = temp\n elif temp > ans2:\n ans2 = temp\n dp[node] = (price[node] + ans1, price[node] + ans2)\n return dp[node][0]\n # dfs2 root node with parent\n def dfs2(node: int, parent: int):\n # reroot\n # remove node\'s contribution from parent\n if parent != -1:\n maxPathSumParentIsolated = dp[parent][0]\n if dp[node][0] + price[parent] == dp[parent][0]:\n maxPathSumParentIsolated = dp[parent][1]\n # Add parent\'s isolated contribution back to node\n ans1, ans2 = dp[node][0], dp[node][1]\n if price[node] + maxPathSumParentIsolated > ans1:\n ans2 = ans1\n ans1 = price[node] + maxPathSumParentIsolated\n elif price[node] + maxPathSumParentIsolated > ans2:\n ans2 = price[node] + maxPathSumParentIsolated \n dp[node] = (ans1, ans2)\n \n for child in graph[node]:\n if child != parent:\n dfs2(child, node)\n \n dfs(0, -1)\n dfs2(0, -1)\n ans = 0\n for node in range(n):\n ans = max(ans, dp[node][0] - price[node])\n return ans\n# old ------------------------------------------------------------------------------\n # The idea revolves around using previous nodes calculation to find answer for the current\n # node.\n # We will do dfs and store max path inside the subtree of a node in f.\n # We will do dfs and store max path outside the subtree of a node in g.\n # We need to stick to an approcah that guarantees linear time complexity. For dfs2 we \n # intentionally calculate parent\'s contribution and pass it to children rather\n # than calculating parent\'s contribution while processing it\'s children.\n \n # Manual rerooting would be easier: dfs1 to calculate max cost for a random root, dfs2 for rerooting.\n\n graph = [[] for _ in range(n)]\n for edge in edges:\n graph[edge[0]].append(edge[1])\n graph[edge[1]].append(edge[0])\n f = [0] * n\n g = [0] * n\n\n # postorder based\n def dfs(node: int, parent: int) -> int:\n ans = 0\n for child in graph[node]:\n if child != parent:\n ans = max(ans, dfs(child, node))\n f[node] = ans + price[node]\n return f[node]\n dfs(0, n)\n\n # preorder based\n def dfs2(node: int, parent: int, parentContribution: int):\n g[node] = parentContribution + price[node]\n topChild = -1\n max1 = max2 = 0\n for child in graph[node]:\n if child != parent:\n if f[child] > max1:\n max2 = max1\n max1 = f[child]\n topChild = child\n elif f[child] > max2:\n max2 = f[child]\n\n for child in graph[node]:\n if child != parent:\n if child == topChild:\n dfs2(child, node, price[node] + max(parentContribution, max2))\n else:\n dfs2(child, node, price[node] + max(parentContribution, max1))\n dfs2(0, n, 0)\n\n ans = 0\n for node in range(n):\n ans = max(ans, max(f[node], g[node]) - price[node])\n return ans\n\n``` | 0 | 0 | ['Python3'] | 0 |
difference-between-maximum-and-minimum-price-sum | Use DFS and ReRoot | use-dfs-and-reroot-by-thevu870-amjt | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n- Use 2 DFS\n- 1st DFS: find biggest path at each sub tree so we can find | thevu870 | NORMAL | 2024-08-28T08:02:39.530209+00:00 | 2024-08-28T08:02:39.530252+00:00 | 13 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n- Use 2 DFS\n- 1st DFS: find biggest path at each sub tree so we can find biggest path of tree start with root = node 0.\n- 2nd DFS: Currently we have info of tree with root = node 0, now if we try to change root from node 0 to node X (X is a child in traversal). we have to update info for node 0 and X.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(3*n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long maxOutput(int n, vector<vector<int>>& edges, vector<int>& price) {\n vector<vector<int>> tree(n, vector<int>());\n for (auto e : edges) {\n tree[e[0]].push_back(e[1]);\n tree[e[1]].push_back(e[0]);\n }\n vector<uint64_t> sub(n, 0);\n vector<set<pair<uint64_t, int>>> subChilds(n, set<pair<uint64_t, int>>());\n function<void(const vector<vector<int>>&, int, int)> DFS = \n [&](const vector<vector<int>>&, int node, int parent) -> void {\n //printf("visit %d\\n", node);\n sub[node] = price[node];\n for (auto c : tree[node]) {\n if (c == parent) continue;\n DFS(tree, c, node);\n sub[node] = max(sub[node], sub[c] + price[node]);\n subChilds[node].insert({sub[c], c});\n }\n\n //printf("visit sub[%d] = %d\\n", node, sub[node]);\n };\n \n DFS(tree, 0, -1);\n\n uint64_t ans = sub[0] - price[0];\n function<void(const vector<vector<int>>&, int, int)> ReRoot = \n [&](const vector<vector<int>>&, int node, int parent) -> void {\n //printf("ReRoot %d\\n", node);\n uint64_t backup_sub_node = 0;\n uint64_t backup_sub_parent = 0;\n if (parent != -1) {\n backup_sub_node = sub[node];\n backup_sub_parent = sub[parent];\n // change root from parent to node\n uint64_t maxChild = 0;\n subChilds[parent].erase({sub[node], node});\n if (!subChilds[parent].empty()) {\n auto it = subChilds[parent].end();\n it--;\n maxChild = it->first;\n }\n\n sub[parent] = price[parent] + maxChild;\n sub[node] = max(maxChild, sub[parent] + price[node]);\n subChilds[node].insert({sub[parent],parent});\n ans = max(ans, sub[node] - price[node]);\n }\n\n for (auto c : tree[node]) {\n if (c == parent) continue;\n ReRoot(tree, c, node);\n }\n\n if (parent != -1) {\n // rollback to visist neighbor\n subChilds[node].erase({sub[parent], parent});\n subChilds[parent].insert({backup_sub_node, node});\n sub[node] = backup_sub_node;\n sub[parent] = backup_sub_parent; \n }\n };\n\n ReRoot(tree, 0, -1);\n\n return ans;\n\n };\n\n\n};\n``` | 0 | 0 | ['C++'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.