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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
maximum-building-height | Java O(1) space O(klogk) time with comments. | java-o1-space-oklogk-time-with-comments-xqous | \n// This is quite similar to 135-Candy https://leetcode.com/problems/candy/\n// \n// Complexity: \n// Time: O(klogk), k is length of restrictions\n// Space: O( | janevans | NORMAL | 2021-04-25T04:02:18.617099+00:00 | 2021-04-25T20:54:59.764985+00:00 | 1,490 | false | ```\n// This is quite similar to 135-Candy https://leetcode.com/problems/candy/\n// \n// Complexity: \n// Time: O(klogk), k is length of restrictions\n// Space: O(1) no extra space is needed\n// \nclass Solution {\n public int maxBuilding(int n, int[][] restrictions) {\n Arrays.sort(restrictions, (a, b) -> Integer.compare(a[0], b[0]));\n // first updata restrictions from left to right\n // this is because there is case that the restriction height cannot be achieved.\n // example\n // H: 0 3 9 \n // ind: 1 2 3\n // because the gap between 2-1 and 3-2 is too small, so the maximum height cannot be achieved, \n // can only achieved:\n // H: 0 1 2 \n // ind: 1 2 3 \n int prevInd = 1, prevH = 0;\n for (int i=0; i<restrictions.length; i++) {\n restrictions[i][1] = Math.min(restrictions[i][1], prevH + (restrictions[i][0] - prevInd));\n prevInd = restrictions[i][0];\n prevH = restrictions[i][1];\n }\n \n // similar but updata restrictions from right to left\n for (int i=restrictions.length-2; i>=0; i--) {\n restrictions[i][1] = Math.min(restrictions[i][1], restrictions[i+1][1] + (restrictions[i+1][0] - restrictions[i][0]));\n }\n \n int ph = 0, pInd = 1, highest = 0;\n for (int i=0; i<restrictions.length; i++) {\n int ind = restrictions[i][0];\n int h = restrictions[i][1];\n if (ph < h) {\n h = Math.min(h, ph + (ind - pInd));\n // if we have remains steps we can achieve a higher height by doing the following\n //example: pInd = 1, ph = 1, ind = 6, h = 2\n // reaching height 1 to height 2 only needs 1 step, but we have (6-1) - 1 = 4 remaing steps\n // we can use the 4 remaining steps to go higher first then back down.\n // The steps are, first move up to 2, then we have 4 steps, go 2 up to height 4, then 2 down back to 2, so highest is 4\n //H 1 2 3 4 3 2\n //ind 1 6\n int remains = Math.max(0, (ind-pInd) - (h - ph));\n highest = Math.max(highest, h + remains/2);\n } else {\n // after the above preprocessing, we must be able to go down from ph to h.\n int remains = (ind-pInd) - (ph-h);\n highest = Math.max(highest, ph + remains/2);\n }\n ph = h;\n pInd = ind;;\n }\n highest = Math.max(highest, ph + (n-pInd));\n return highest;\n }\n}\n``` | 12 | 0 | [] | 3 |
maximum-building-height | Java | O(NlogN) | java-onlogn-by-changeme-r8du | Intuition\nIf you have no limits, you can have a building with height n - 1. Example 2 in the problem.\nSequence of building: 0, 1, 2, 3, 4, 5\n\nRestrictions h | changeme | NORMAL | 2021-04-25T04:01:28.549616+00:00 | 2021-04-25T08:29:35.836062+00:00 | 861 | false | **Intuition**\nIf you have no limits, you can have a building with height `n - 1`. Example 2 in the problem.\nSequence of building: 0, 1, 2, 3, 4, 5\n\nRestrictions have effect on buildings from the left and from the right:\nExample with height restrion 1 at 3:\n0, 1, **1**, **2,** **3**, **4** ..\nThis restriction has effect on the buildings 3, 4, 5, 6 ..\n\nExample with height restrion 0 at 5:\n0, 1, 2, **1**, **0**\nThis restriction has effect on the buildings 5 and 4\n\n**Solution**\n1. Adjust restrinctions from the left and from the right.\n2. Calculate max height that you can get in between of two restrictions.\n\n```\npublic int maxBuilding(int n, int[][] rr) {\n\tint[][] r = new int[rr.length + 2][];\n\tfor (int i = 0; i < rr.length; i++) {\n\t\tr[i] = rr[i];\n\t}\n\t// extra restriction for building 1\n\tr[r.length - 2]= new int[] { 1, 0 };\n\t// extra restriction for the last building\n\tr[r.length - 1]= new int[] { n, 1_000_000_000 };\n\tArrays.sort(r, (a,b) -> a[0] - b[0]);\n\n\t// Adjust restrictions from the left\n\tfor (int i = 1; i < r.length; i++) {\n\t\tint d = r[i][0] - r[i - 1][0];\n\t\tr[i][1] = Math.min(r[i][1], r[i - 1][1] + d);\n\t}\n\t\n\t// Adjust restrictions from the right\n\tfor (int i = r.length - 2; i >= 0; i--) {\n\t\tint d = r[i + 1][0] - r[i][0];\n\t\tr[i][1] = Math.min(r[i][1], r[i + 1][1] + d);\n\t}\n\t\n\tint res = 0;\n\t\n\t// Calculate max height that you can get in between of two restrictions (that\'s why we need those extra two restrictions)\n\tfor (int i = 1; i < r.length; i++) {\n\t\tint d = r[i][0] - r[i - 1][0];\n\t\tint max = Math.max(r[i][1], r[i - 1][1]);\n\t\tres = Math.max(res, max);\n\t\tint min = Math.min(r[i][1], r[i - 1][1]);\n\t\td = d - (max - min);\n\t\tres = Math.max(res, max + d / 2);\n\t}\n\t\n\treturn res;\n}\n``` | 10 | 0 | [] | 1 |
maximum-building-height | Python3. O(N*log(N)). Using stack. Explanation added. | python3-onlogn-using-stack-explanation-a-llbf | \n# Logic:\n# 1. Filter out all restrictions that don\'t change anything.\n# For example:\n# there are two conditions:\n# - building with inde | yaroslav-repeta | NORMAL | 2021-04-25T04:02:40.869999+00:00 | 2021-04-25T04:54:29.104787+00:00 | 653 | false | ```\n# Logic:\n# 1. Filter out all restrictions that don\'t change anything.\n# For example:\n# there are two conditions:\n# - building with index 5 has max height 1\n# - building with index 6 has max height 10\n# we don\'t care about the second condition, because the first one is stricter\n# and forces the building with index 6 to have max height 2\n# If to generalize:\n# if we have two restrictions: (index_1, max_height_1) and (index_2, max_height_2)\n# and abs(index_1 - index_2) < abs(max_height_1 - max_height_2)\n# then we can ignore a restriction with larger max_height\n# 2. Iterate through restrictions left and simply compute the max possible building between them.\n# It can be done as: max_building_in_between = (left_height + right_height + right_index - left_index) // 2\n\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n # sort, so we can compare adjacent restrictions\n restrictions.sort()\n stack = [(1, 0)]\n for i, max_height in restrictions:\n # check if current restriction is stricter than the last one in the stack; pop one if yes\n while stack and i - stack[-1][0] <= stack[-1][1] - max_height:\n stack.pop()\n # check if the last restriction in the stack is stricter than current one; if no add current one to the stack\n if not stack or i - stack[-1][0] > max_height - stack[-1][1]:\n stack.append((i, max_height))\n res = 0\n for i in range(1, len(stack)):\n res = max(res, (stack[i][1] + stack[i - 1][1] + stack[i][0] - stack[i - 1][0]) // 2)\n return max(res, stack[-1][1] + n - stack[-1][0])\n \n``` | 9 | 0 | [] | 1 |
maximum-building-height | [Python] rotate by 45 | python-rotate-by-45-by-zdu011-dk20 | We can rotate all restrictions clockwise by 45 degrees. The skyline of the buildings after this rotation will be rectangles with sides parallel to x or y-axis a | zdu011 | NORMAL | 2021-04-25T04:00:43.422009+00:00 | 2021-04-25T04:10:22.940654+00:00 | 832 | false | We can rotate all restrictions clockwise by 45 degrees. The skyline of the buildings after this rotation will be rectangles with sides parallel to x or y-axis and the highest buildings correspond to the corners of these rectangles.\n\n```\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n points=[[0,0]]\n # whether there\'s a restriction on x==n\n found=False \n for x,y in restrictions:\n if x==n:\n found=True\n x-=1 \n # rotate the points clockwise by 45 degrees\n points.append([x+y,y-x])\n \n # if no restrictions on x==n, add a restriction with x=n, y=inf\n if not found:\n points.append([(n-1)+10**10,10**10-(n-1)])\n \n # sort the points by the new x coordinates\n points.sort()\n ans=0\n last_y=points[0][1]\n for xp,yp in points[1:]:\n if yp>last_y:\n ans=max(ans,(xp-yp)//2+last_y)\n continue\n # find the corner formed by the current vertical side and the last horizontal side\n ans=max(ans,(xp+last_y)//2)\n last_y=yp\n \n return ans\n``` | 7 | 0 | [] | 1 |
maximum-building-height | [Python3] greedy | python3-greedy-by-ye15-lhja | \n\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n restrictions.extend([[1, 0], [n, n-1]])\n restrict | ye15 | NORMAL | 2021-04-25T04:02:06.522071+00:00 | 2021-04-25T16:15:09.447931+00:00 | 497 | false | \n```\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n restrictions.extend([[1, 0], [n, n-1]])\n restrictions.sort()\n \n for i in reversed(range(len(restrictions)-1)): \n restrictions[i][1] = min(restrictions[i][1], restrictions[i+1][1] + restrictions[i+1][0] - restrictions[i][0])\n \n ans = 0 \n for i in range(1, len(restrictions)): \n restrictions[i][1] = min(restrictions[i][1], restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0])\n ans = max(ans, (restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0] + restrictions[i][1])//2)\n return ans \n``` | 6 | 2 | ['Python3'] | 0 |
maximum-building-height | C++ Filter Critical Restrictions | c-filter-critical-restrictions-by-lzl124-iaa1 | See my latest update in repo LeetCode\n## Solution 1. Filter Critical Restrictions\n\nWe should remove the useless restrictions and only keep the critical ones. | lzl124631x | NORMAL | 2021-04-25T04:00:35.550917+00:00 | 2021-04-25T05:12:00.183994+00:00 | 822 | false | See my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n## Solution 1. Filter Critical Restrictions\n\nWe should remove the useless restrictions and only keep the critical ones.\n\n### Step 1. Remove Useless Restrictions\n\nPut all the restrictions into a `m` which is a map from the `x` value to the height restriction. Note that `m[1] = 0` should also be added.\n\nScan from left to right, assume two consecutive restrictions are `a = [x1, h1]` and `b = [x2, h2]` (`x1 < x2`). If `h2 >= h1 + x2 - x1`, `b` is useless and should be removed.\n\nScan from right to left, assume two consecutive restrictions are `a = [x1, h1]` and `b = [x2, h2]` (`x1 < x2`). If `h1 >= h2 + x2 - x1`, `a` is useless and should be removed.\n\n### Step 2. Calculate the max heights we can get between two consecutive restrictions\n\nFor two consecutive restrictions are `a = [x1, h1]` and `b = [x2, h2]` (`x1 < x2`), assume the tallest building between them is at position `x`, then one of the following is is true:\n\n* When there is only one tallest building, `h1 + x - x1 == h2 + x2 - x`, so `2 * x = h2 - h1 + x1 + x2`\n* When there are two tallest buildings, `h1 + x - x1 == h2 + x2 - x - 1`, so `2 * x = h2 - h1 + x1 + x2 - 1`.\n\nSo `x = ceil( (h2 - h1 + x1 + x2) / 2 )`, and the corresponding height is `h1 + x - x1`.\n\nOne special case is the last restriction `[x, h]`. The height we can get using it is `h + n - x`.\n\n```cpp\n// OJ: https://leetcode.com/contest/weekly-contest-238/problems/maximum-building-height/\n// Author: github.com/lzl124631x\n// Time: O(RlogR)\n// Space: O(R)\nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& A) {\n map<long, long> m{{1,0}};\n for (auto &v : A) m[v[0]] = v[1];\n long ans = 0;\n for (auto it = next(begin(m)); it != end(m);) {\n auto [x1, h1] = *prev(it);\n auto [x2, h2] = *it;\n if (h2 >= h1 + x2 - x1) {\n it = m.erase(it);\n } else {\n it = next(it);\n }\n }\n for (auto it = prev(end(m)); it != begin(m);) {\n auto [x1, h1] = *prev(it);\n auto [x2, h2] = *it;\n if (h1 >= h2 + x2 - x1) {\n m.erase(prev(it));\n } else {\n it = prev(it);\n }\n }\n for (auto it = next(begin(m)); it != end(m); ++it) {\n auto [x1, h1] = *prev(it);\n auto [x2, h2] = *it;\n long x = (h2 - h1 + x1 + x2) / 2;\n ans = max(ans, h1 + x - x1);\n }\n auto [x, h] = *rbegin(m);\n ans = max(ans, h + n - x);\n return ans;\n }\n};\n``` | 6 | 0 | [] | 0 |
maximum-building-height | Java DP O(mlogm) | java-dp-omlogm-by-mayank12559-kfvx | \npublic int maxBuilding(int n, int[][] restrictions) {\n int m = restrictions.length;\n if(m == 0){\n return n-1;\n }\n | mayank12559 | NORMAL | 2021-04-25T04:00:36.481490+00:00 | 2021-04-30T16:14:18.380715+00:00 | 440 | false | ```\npublic int maxBuilding(int n, int[][] restrictions) {\n int m = restrictions.length;\n if(m == 0){\n return n-1;\n }\n Arrays.sort(restrictions, (a,b) -> a[0]-b[0]);\n int []dp = new int[m]; // dp[i] => maximum allowed height at restriction[i][0]th building\n dp[0] = Math.min(restrictions[0][1], restrictions[0][0]-1);\n for(int i=1;i<m;i++){\n dp[i] = Math.min(restrictions[i][0] - restrictions[i-1][0] + dp[i-1], restrictions[i][1]);\n }\n for(int i=m-2;i>=0;i--){\n dp[i] = Math.min(dp[i], dp[i+1] + restrictions[i+1][0] - restrictions[i][0]);\n }\n int max = Math.max(dp[0],n - restrictions[m-1][0] + dp[m-1]);\n for(int i=1;i<m;i++){\n max = Math.max(max, Math.max(dp[i], dp[i-1]) + (restrictions[i][0] - restrictions[i-1][0] - Math.abs(dp[i]-dp[i-1]))/2);\n }\n\t\tmax = Math.max(max, (restrictions[0][0]-1)/2);\n return max;\n }\n``` | 5 | 1 | [] | 0 |
maximum-building-height | JAVA Solution | java-solution-by-himanshuchhikara-l5gv | EXPLANATION:\n\nyou can see in the given example first we need to reduce height of 11 from left i.e to 5 . then from right i.e to 4. So we need two iteration o | himanshuchhikara | NORMAL | 2021-04-25T09:55:57.732666+00:00 | 2021-04-29T04:42:42.485720+00:00 | 746 | false | **EXPLANATION:**\n\nyou can see in the given example first we need to reduce height of 11 from left i.e to 5 . then from right i.e to 4. So we need two iteration one from left and then one from right.\nAnd I have added 1st id(to set the heigth through iterations) and last id also(heighest height) . \n\n\nIf x and y have same height maximum heigth will lie in between can find that by h + (x-y)/2 \n\nBut if height are unequal then Math.max(h1,h2) + (x-y - (Math.abs(h1-h2))/2;\n\nAnd check for every height .\n\n**CODE:**\n```\nclass Solution {\n public int maxBuilding(int n, int[][] restrictions) {\n List<int[]> list=new ArrayList<>();\n list.add(new int[]{1,0});\n for(int[] restriction:restrictions){\n list.add(restriction);\n }\n Collections.sort(list,new IDSorter());\n \n if(list.get(list.size()-1)[0]!=n){\n list.add(new int[]{n,n-1});\n }\n \n for(int i=1;i<list.size();i++){\n list.get(i)[1]=Math.min(list.get(i)[1],list.get(i-1)[1] + list.get(i)[0]-list.get(i-1)[0]);\n }\n \n for(int i=list.size()-2;i>=0;i--){\n list.get(i)[1]=Math.min(list.get(i)[1],list.get(i+1)[1] + list.get(i+1)[0] - list.get(i)[0]);\n } \n \n int result=0;\n for(int i=1;i<list.size();i++){\n int h1=list.get(i-1)[1]; // heigth of previous restriction\n int h2=list.get(i)[1]; // height of current restriction\n int x=list.get(i-1)[0]; // id of previous restriction\n int y=list.get(i)[0]; // id of current restriction\n \n result=Math.max(result,Math.max(h1,h2) + (y-x-Math.abs(h1-h2))/2);\n } \n return result;\n }\n \n public class IDSorter implements Comparator<int[]>{\n @Override\n public int compare(int[] myself,int[] other){\n return myself[0]-other[0];\n } \n }\n}\n```\n\n**Complexity :**\n`Time:O(nlogn) and Space:O(n)`\n\nI have understood it from [here](https://leetcode.com/problems/maximum-building-height/discuss/1175343/C%2B%2B-Step-by-step-video-explanation-in-and-English) and its a best possible explanation for this. All credit to that guy I have just wrote the java version of that for java coders.\n\nPlease **UPVOTE** if you found it helpful and feel free to reach out to me or comment down if you have any doubt. | 4 | 0 | ['Java'] | 1 |
maximum-building-height | [Python] Math - McShane extension operator | python-math-mcshane-extension-operator-b-5cn8 | The solution to this problem can be viewed as mild generalization of McShane\'s extension theorem, which is an easy special case of Kirszbraun\'s theorem. McSha | kevinfederline | NORMAL | 2021-04-25T04:56:30.615841+00:00 | 2021-04-25T04:58:46.017966+00:00 | 325 | false | The solution to this problem can be viewed as mild generalization of McShane\'s extension theorem, which is an easy special case of [Kirszbraun\'s theorem](https://en.wikipedia.org/wiki/Kirszbraun_theorem). McShane\'s theorem concerns extension of functions satisfying a Lipschitz condition. Specifically, suppose E is a subset of R^n (or more generally, any metric space X) and f : E to R is 1-Lipschitz. That is, |f(x) - f(y)| <= |x-y| for any x, y in E. Then the function F(x) = inf{f(y) + |y-x| : y in E} is 1-Lipschitz and extends f to all of R^n (or more generally X). This is quite easy to prove. It\'s also not so hard to see that McShane\'s extension is maximal among all Lipschitz extensions of f. That is, if G : R^n to R is 1-Lipschitz and G(x) = f(x) for all x in E, then G(x) <= F(x) for all x in R^n.\n\nNow suppose f is L-Lipschitz for L > 1. Define F as above. It is no longer the case that F(x) = f(x) for x in E, but it is still the case that F is 1-Lipschitz. Indeed, it\'s not hard to show that F is maximal among 1-Lipschitz functions with the property that F(x) <= f(x) for all x in E.\n\nThe point is that this F gives the solution to the problem. Here\'s the code:\n\n```\ndef rectify(limits):\n for i in range(1, len(limits)):\n if limits[i][1] - limits[i-1][1] > limits[i][0] - limits[i-1][0]:\n limits[i][1] = limits[i-1][1] + limits[i][0] - limits[i-1][0]\n for i in range(len(limits)-1)[::-1]:\n if limits[i][1] - limits[i+1][1] > limits[i+1][0] - limits[i][0]:\n limits[i][1] = limits[i+1][1] + limits[i+1][0] - limits[i][0]\n return limits\n\ndef get_max_height(lim1, lim2):\n lo, lo_height = lim1\n hi, hi_height = lim2\n max_height, min_height = sorted([lo_height, hi_height])\n return max_height + (hi - lo - (max_height - min_height)) // 2\n\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n restrictions.append([1, 0])\n restrictions.sort()\n if restrictions[-1][0] != n:\n restrictions.append([n, n])\n restrictions = rectify(restrictions)\n res = 0\n for i in range(1, len(restrictions)):\n res = max(res, get_max_height(restrictions[i-1], restrictions[i]))\n return res\n``` | 4 | 0 | [] | 1 |
maximum-building-height | [Java] Greedy Clean Solution with explanation - O(mlogm) | java-greedy-clean-solution-with-explanat-1hix | Use Greedy idea\n\nlike leetcode 135, it\'s a two pass greedy problem\n\n time: O(mlogm)\n space: O(m)\n \n\n### step 0. clone a new array, add 2 more | timmybeeflin | NORMAL | 2021-08-27T14:35:48.254290+00:00 | 2021-10-07T13:46:52.218523+00:00 | 336 | false | ## Use Greedy idea\n\nlike leetcode 135, it\'s a two pass greedy problem\n\n time: O(mlogm)\n space: O(m)\n \n\n### step 0. clone a new array, add 2 more space\n\nr[r.length-2] = new int[]{1, 0}; // add first building\nr[r.length-1] = new int[]{n, 1_000_000_000}; // add n building\n\ndo sort, make position right\n\nstart to find upper bound, lower bound to satisfy with limitaions: \n* restrictions[i] = [idi, maxHeighti]\n* The height difference between any two adjacent buildings cannot exceed 1\n\n\n\n### step 1. from right <----\n```\n <------------- \n\n |\n | \n| | | \n| | |\n i. i+1 => position\n```\nfor limitaion\n```\n (high diff) must >= (dist)\n\t\n r[i][1] - r[i+1][1] >= r[i+1][0] - r[i][0]\n \n=> r[i][1] = min(r[i][1], r[i+1][1] + r[i+1][0] - r[i][0])\n```\n\nwhy we compare distance with height diff?\n\nfrom problem descrption:\n**The height difference between any two adjacent buildings cannot exceed 1**\nso each one distance, there is a building => one distance, building\'s height can grow only one.\n\nfrom right [i+1] building to [i] building, we can conclude\n```\nr[i][1] - r[i+1][1] >= r[i+1][0] - r[i][0]\n\nor just\n\nr[i][1] - r[i+1][1] = r[i+1][0] - r[i][0]\n```\n\nso we can get\n```\nr[i][1] = min(r[i][1], r[i+1][1] + r[i+1][0] - r[i][0])\n```\n\n### step 2. from left ---->\n\nlike looking from right: \n\n```\n (high diff) must >= (dist)\n \n r[i][1] - r[i-1][1] >= r[i][0] - r[i-1][0] \n \n=> r[i][1] = Math.min(r[i][1], r[i-1][1] + r[i][0] - r[i-1][0]);\n```\n\n\n\n### step 3. last step: caculate the peak of two limit building (each buildings), and keep updating the max peak\n\nex1: same height\n```\n p => peak\n \n4. 4. => hight\nx y => position\ndist = y - x\np = 4 + (dist)/2 \n \n```\n\nex2: different height\n```\n p => peak\n\n3 4 => hight\nx. y. => position\n\n3 needs to add 1 to 4, fix to same high, this fix: 1 will substract from dist(y-x)\n\ndist = y - x\ndiff of hight = 4 -3 = 1\np = 4 + (dist - diff of hight)/2 \n```\n\n```\nclass Solution {\n public int maxBuilding(int n, int[][] restrictions) {\n int[][] r = new int[restrictions.length+2][];\n for (int i = 0; i < restrictions.length; i++) {\n r[i] = restrictions[i];\n }\n r[r.length-2] = new int[]{1, 0}; // add first building\n r[r.length-1] = new int[]{n, 1_000_000_000}; // add n building\n \n Arrays.sort(r, (a, b) -> a[0] - b[0]);\n \n int m = r.length;\n \n for (int i = m-2; i >= 1; i--) { // from right <-\n r[i][1] = Math.min(r[i][1], r[i+1][1] + r[i+1][0] - r[i][0]);\n }\n \n int res = 0;\n for (int i = 1; i < m; i++) { // from left ->\n r[i][1] = Math.min(r[i][1], r[i-1][1] + r[i][0] - r[i-1][0]);\n \n // last step: caculate the peak of two limit building (each buildings)\n int distance = r[i][0] - r[i-1][0];\n\t\t\tint buildDiff = Math.abs(r[i][1] - r[i-1][1])\n\t\t\tint peak = (distance - buildDiff)/2;\n\t\t\tint maxBuildingHeight\t=\tMath.max(r[i][1], r[i-1][1]);\n res = Math.max(res, maxBuilding + peak);\n }\n \n return res;\n }\n}\n``` | 3 | 0 | [] | 0 |
maximum-building-height | Runtime beats 92.00% [EXPLAINED] | runtime-beats-9200-explained-by-r9n-bkoc | Intuition\nFinding the tallest possible building height under specific constraints, where the height of buildings must not exceed given limits, and heights must | r9n | NORMAL | 2024-10-17T08:10:28.739485+00:00 | 2024-10-17T08:10:28.739516+00:00 | 61 | false | # Intuition\nFinding the tallest possible building height under specific constraints, where the height of buildings must not exceed given limits, and heights must gradually increase or decrease by at most one between adjacent buildings.\n\n# Approach\nStart by adding the first and last buildings to the restrictions, sort the restrictions, then perform a forward pass to calculate maximum possible heights for each building based on previous restrictions, followed by a backward pass to ensure the heights do not exceed future restrictions, finally compute the maximum possible height between the adjusted restrictions.\n\n# Complexity\n- Time complexity:\nO(m log m), where m is the number of restrictions, due to sorting and linear passes.\n\n- Space complexity:\nO(m) for storing the adjusted restrictions.\n\n# Code\n```python3 []\nclass Solution:\n def maxBuilding(self, n: int, restrictions: list[list[int]]) -> int:\n # Add the first building and the last building to the restrictions\n restrictions.append([1, 0])\n restrictions.append([n, n]) # Last building can be at max height n\n # Sort restrictions by building ID\n restrictions.sort()\n \n # Forward pass: Calculate the maximum possible height\n for i in range(1, len(restrictions)):\n id_prev, height_prev = restrictions[i - 1]\n id_curr, height_curr = restrictions[i]\n # Calculate the max height for buildings between id_prev and id_curr\n distance = id_curr - id_prev\n max_height = height_prev + distance\n restrictions[i][1] = min(height_curr, max_height)\n \n # Backward pass: Adjust heights based on restrictions\n for i in range(len(restrictions) - 2, -1, -1):\n id_prev, height_prev = restrictions[i]\n id_curr, height_curr = restrictions[i + 1]\n # Calculate the max height for buildings between id_curr and id_prev\n distance = id_curr - id_prev\n max_height = height_curr + distance\n restrictions[i][1] = min(height_prev, max_height)\n\n # Calculate the maximum possible height\n max_height = 0\n for i in range(1, len(restrictions)):\n id_prev, height_prev = restrictions[i - 1]\n id_curr, height_curr = restrictions[i]\n # Height at midpoint\n max_height = max(max_height, (height_prev + height_curr + (id_curr - id_prev)) // 2)\n\n return max_height\n\n\n\n``` | 2 | 0 | ['Python3'] | 0 |
maximum-building-height | [C++] O(n log n) Greedy + Sorting | c-on-log-n-greedy-sorting-by-alexunxus-ldlx | Intuition and Approach\n Describe your first thoughts on how to solve this problem. \n\n## First step: Make restrictions achievable!\nFirstly, the restrictions | alexunxus | NORMAL | 2023-02-03T02:42:15.318436+00:00 | 2023-02-03T03:28:25.674017+00:00 | 144 | false | # Intuition and Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n## First step: Make restrictions achievable!\nFirstly, the restrictions may not hold true due to the constraint "the height differences between every two adjacent building should not exceed 1". For example:\n\n```\n0 2 15 2 <- restriction\n1 2 3 4 5 6 7 <- position\n```\n\nThe restriction at position 3 can be achieved by \n```\n0 2 15 2 <- restriction\n0 1 2 3 4 3 2 <- actual height\n1 2 3 4 5 6 7 <- position\n```\nHowever, the restriction at position 5 is not achievable. We can first sort the restrictions by their horizontal position and scan from left to right and check if $(x_i, r_i) (x_{i+1}, r_{i+1})$ satisfies:\n$$r_{i+1} <= r_{i} + (x_{i+1} - x_i)$$, if not, we should set $r_{i+1} = r_{i} + (x_{i+1} - x_i)$. \nBy doing so, we can always guarantee when moving from lower x coordinate to higher ones, the higher restrictions is always "within the reach" of the previous one.\n\nHowever, we should do the same check from right to left. So when finishing the left-to-right check, we have to do the right-to-left check:\n$$r_{i} <= r_{i+1} + (x_{i+1} - x_i)$$, if not, we should set $r_{i} = r_{i+1} + (x_{i+1} - x_i)$. Then now all the restrictions are achieveable.(so I will now replace $r_i$, with $y_i$)\n\nFinally there is some implementation details. For example, we should add (1, 0) as one of the constraint. In addition, we should also bound the postion at $n$ by a large integer(e.g. 1e9, think about why? hint: the restriction at 1 is 0).\n\n## Second step: Find the maximal height between every adjacent buildings with restrictions\nThe next part is to fill the gap between two restricted position. For $(x_i, y_i), (x_{i+1}, y_{i+1})$, we hope we can keep building on the line \n$$y = x - x_i + y_i$$ to maximize the height within $[x_i, x_{i+1}]$.\n\nFrom the opposite direction, we hope to build the houses on the trajectory\n$$y = -(x - x_{i+1}) + y_{i+1}$$.\n\nHowever, for position $x_i < x < x_{i+1}$, we should build it with height \n$$\\min(x - x_i + y_i, -(x - x_{i+1}) + y_{i+1})$$. An easy way is to find the intersection of these two lines. If they intersect beyound the interval, the highest building must lie on either $x_i$ or $x_{i+1}$. If they intersect within the interval, we should check the height of the intersection.\n``` \n /\n / \\\n / \\\n \u53E3 \\\n \u53E3 \u53E3\n____\u53E3 \u53E3________\n```\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$O(n\\log n)$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$O(quicksort)$\n\n# Code\n```\nstruct Point {\n int x, y;\n Point() {x = y = 0;}\n Point(const int & _x, const int & _y) {\n x = _x, y = _y;\n }\n\n bool operator<(const Point & p) {\n return x == p.x?y <= p.y:x<p.x;\n }\n};\n\nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& restrictions) {\n vector<Point> pts;\n for (auto & r: restrictions) {\n pts.push_back({r[0], r[1]});\n }\n pts.push_back({1, 0});\n ::sort(begin(pts), end(pts));\n if (pts.back().x != n) {\n pts.push_back({n, 1000000000});\n }\n \n int sz = pts.size();\n for (int i = 0; i < sz-1; ++i) {\n int xdiff = pts[i+1].x - pts[i].x;\n if (pts[i+1].y > pts[i].y + xdiff) {\n pts[i+1].y = pts[i].y + xdiff;\n }\n }\n for (int i = sz-2; i>= 0; --i) {\n int xdiff = pts[i+1].x - pts[i].x;\n if (pts[i].y > pts[i+1].y + xdiff) {\n pts[i].y = pts[i+1].y + xdiff;\n }\n }\n int h = 0;\n for (int i = 0; i < sz-1; ++i) {\n h = max(h, max(pts[i].y, pts[i+1].y));\n int x1 = pts[i].x, x2 = pts[i+1].x;\n int y1 = pts[i].y, y2 = pts[i+1].y;\n int twox = x1+x2+y2-y1;\n if (twox >= 2*x1 && twox <= 2*x2) {\n int mid = twox/2;\n int newy = y1 + mid - x1;\n h = max(newy, h);\n }\n }\n return h;\n }\n};\n```\n\n## Optimized Two Pass Solution\n```\nstruct Point {\n int x, y;\n Point() {x = y = 0;}\n Point(const int & _x, const int & _y) {x = _x, y = _y;}\n\n bool operator<(const Point & p) {\n return x == p.x?y <= p.y:x<p.x;\n }\n};\n\nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& restrictions) {\n vector<Point> pts;\n for (auto & r: restrictions) {\n pts.push_back({r[0], r[1]});\n }\n pts.push_back({1, 0});\n ::sort(begin(pts), end(pts));\n if (pts.back().x != n) {\n pts.push_back({n, n-1});\n }\n\n int sz = pts.size(), hmax = 0;\n for (int i = 0; i < sz-1; ++i) {\n int h = pts[i].y + pts[i+1].x - pts[i].x;\n if (pts[i+1].y > h) {\n pts[i+1].y = h;\n }\n }\n for (int i = sz-2; i>= 0; --i) {\n int h = pts[i+1].y + pts[i+1].x - pts[i].x;\n if (pts[i].y < h) {\n h = (pts[i].y + h)/2;\n }\n hmax = max(h, hmax);\n pts[i].y = min(pts[i].y, h);\n }\n return hmax;\n }\n};\n``` | 2 | 0 | ['Greedy', 'Sorting', 'C++'] | 0 |
maximum-building-height | (C++) 1840. Maximum Building Height | c-1840-maximum-building-height-by-qeetco-q1mr | \n\nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& restrictions) {\n restrictions.push_back({1, 0});\n restrictions.pu | qeetcode | NORMAL | 2021-04-25T16:50:11.674877+00:00 | 2021-04-25T16:50:11.674915+00:00 | 355 | false | \n```\nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& restrictions) {\n restrictions.push_back({1, 0});\n restrictions.push_back({n, n-1}); \n sort(restrictions.begin(), restrictions.end()); \n for (int i = restrictions.size()-2; i >= 0; --i) {\n restrictions[i][1] = min(restrictions[i][1], restrictions[i+1][1] + restrictions[i+1][0] - restrictions[i][0]); \n }\n \n int ans = 0; \n for (int i = 1; i < restrictions.size(); ++i) {\n restrictions[i][1] = min(restrictions[i][1], restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0]); \n ans = max(ans, (restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0] + restrictions[i][1])/2); \n }\n return ans; \n }\n};\n``` | 2 | 0 | ['C'] | 0 |
maximum-building-height | C++ Solution | c-solution-by-6cdh-v70o | The restriction of a[i] affects the buildings after and before it. So I scan the array twice to spread the restricton of a[i].\n\nThe restriction array a splits | 6cdh | NORMAL | 2021-04-25T12:22:09.320975+00:00 | 2021-04-25T12:28:08.700766+00:00 | 230 | false | The restriction of `a[i]` affects the buildings after and before it. So I scan the array twice to spread the restricton of `a[i]`.\n\nThe restriction array `a` splits the `n` buildings into some segments. We can calculate the tallest building of each segments and get the tallest one of all buildings.\n\nTo maximize the height of a segment, the buildings should be built as follows:\n\n```\n /\\ <-- the tallest building in the segment\n / \\\n / \\\n / \\\n/ \\\n^ ^\n| |\n| end of the segment\nstart of the segment\n```\n\nThat is increasing the buildings first, then decreasing.\n\n```c++\nclass Solution {\n public:\n int maxBuilding(int n, vector<vector<int>>& rest) {\n rest.push_back({1, 0});\n rest.push_back({n, n - 1});\n const auto m = rest.size();\n\n sort(rest.begin(), rest.end());\n\n\t\t// left to right\n for (int i = 1; i != m; ++i) {\n rest[i][1] =\n min(rest[i][1], rest[i - 1][1] - rest[i - 1][0] + rest[i][0]);\n }\n\n\t\t// right to left\n for (int i = m - 1; i-- != 0;) {\n rest[i][1] =\n min(rest[i][1], rest[i + 1][1] - rest[i][0] + rest[i + 1][0]);\n }\n\n int max_height = 0;\n for (int i = 1; i != m; ++i) {\n\t\t\t// Let `d = rest[i][0] - rest[i - 1][0]`\n\t\t\t// Assume the tallest height in this segment is `rest[i - 1][1] + h`.\n\t\t\t// So `rest[i - 1][1] + h - (d - h) = rest[i][0] - rest[i - 1][0]`. Solve this equation to get `h`.\n const int height =\n rest[i - 1][1] +\n (rest[i][0] - rest[i - 1][0] - rest[i - 1][1] + rest[i][1]) / 2;\n\n max_height = max(max_height, height);\n }\n\n return max_height;\n }\n};\n``` | 2 | 0 | ['C'] | 0 |
maximum-building-height | [C++] clean code and detailed explanation | c-clean-code-and-detailed-explanation-by-fz6w | At first , it\'s not difficult to work out the max height between two buildings.\n\nCase study\n\nconsidering the following restractions:\n\n1) Building #1 max- | haoel | NORMAL | 2021-04-25T08:29:27.406041+00:00 | 2021-04-25T08:43:03.009814+00:00 | 285 | false | At first , it\'s not difficult to work out the max height between two buildings.\n\n**Case study**\n\nconsidering the following restractions:\n\n1) Building #1 `max-height = 1`, Building #5 `max-height = 1`\n then we can have the building height list - `[1,2,3,2,1] `\n\n2) Building #1 `max-height = 3`, Building #5 `max-height = 1`\n then we can have the building height list - `[3,4,3,2,1]` \n\n3) Building #1 `max-height = 1`, Building #5 `max-height = 9`\n then we can have the building height list - `[1,2,3,4,5]`\n\nSo, we can figure out the following rules :\n\n1) if two restraction has same limited height, suppose we have `[n ......... n]`, \n then we can have the building height list `[n, n+1, n+2, ... n+m-1, n+m, n+m-1 ..., n+2, n+1, n]`\n\t \n\t So, **`m = width /2`** - the `width` is the number of buildings. \n\t \n2) if two restraction has different limited height, suppose we have `[n ...... n+x]`\n then we still can have the building height list like 1) - we just add some buildings behind `[n .... n+x, (n+x-1... n) ]`\n\t\n\tSo, **`m = (width+x)/2`** - we need to extend x buildings\n\n3) if there hasn\'t enough buildings between two restractions. then, the max height we can make is **`width`**. For examples:\n - Building#1 max-height = 2, building#3 max-height = 5 : then, we only can make `[2,3,4]`\n - Building#1 max-height = 2, building#2 max-height = 9 : then, we only can make `[2,3]`\n\nSo, we can have the following source code to calculate the max height between two restractions.\n\n```\n int getMaxHeight(vector<int>& left, vector<int>& right) {\n \n int width = right[0] - left[0];\n int height_delta = abs(right[1] - left[1]);\n int min_height = min (left[1], right[1]);\n \n //if the `width` is enough to have `height_delta`\n if (width >= height_delta) return min_height + (width + height_delta) / 2;\n \n // if the `width` is not enought have `height_delta`\n // then, the `width` is the max height we can make\n int max_height = min_height + width;\n \n return max_height;\n }\n```\n\nBUT, we still have a case need to deal with, considering we have the following restractions:\n\n`[1,1], [2,2] ,[3,3], [4,0]`\n\nwe can process them couple by couple.\n\n- step 1: `[1,1], [2,2]` : max-height = 2\n- step 2: `[2,2] ,[3,3]` : max-height = 3\n- step 3: `[3,3], [4,0]` : max-height = 1\n\nfor the last couple of restractions, we can see the building#3 max-height is 1, so we have go backwards to recaluate the building#2 and building#1.\n\n- step 3: `[3,1], [4,0]` : max-height = 1 (change the `[3,3]` to `[3,1]` )\n- step:4: `[2,2] ,[3,1]` : max-height = 2\n- step 5: `[1,1], [2,2]` : max-height = 2\n\nSo, the correct answer of max height is `2`\n\nfinally, we have the whole source code with debug code inside.\n\n```\nclass Solution {\nprivate:\n void print(vector<vector<int>>& vv){\n cout << "[" ;\n for(int i = 0; i < vv.size()-1; i++) {\n cout << "[" <<vv[i][0] << "," << vv[i][1] << "],";\n }\n int i = vv.size() - 1;\n cout << "[" << vv[i][0] << "," << vv[i][1] << "]]" << endl;\n }\n \npublic:\n int getMaxHeight(vector<int>& left, vector<int>& right) {\n \n int width = right[0] - left[0];\n int height_delta = abs(right[1] - left[1]);\n int min_height = min (left[1], right[1]);\n \n //if the `width` is enough to have `height_delta`\n if (width >= height_delta) return min_height + (width + height_delta) / 2;\n \n // if the `width` is not enought have `height_delta`\n // then, the `width` is the max height we can make\n int max_height = min_height + width;\n \n // if the restriction is higher then make it to right limitation.\n left[1] = min (left[1], max_height);\n right[1] = min (right[1], max_height);\n \n return max_height;\n }\n \n int maxBuilding(int n, vector<vector<int>>& restrictions) {\n restrictions.push_back({1,0});\n restrictions.push_back({n, n-1});\n sort(restrictions.begin(), restrictions.end());\n \n //print(restrictions);\n \n for(int i=0; i<restrictions.size()-1; i++){\n int height = getMaxHeight(restrictions[i], restrictions[i+1]);\n //cout << "[" << restrictions[i][0] << "," << restrictions[i][1]<< "] - " \n // << "[" << restrictions[i+1][0] << "," << restrictions[i+1][1]<< "] = " \n // << height << endl;\n }\n cout << endl;\n int maxHeight = 0;\n for(int i= restrictions.size()-1; i>0; i--){\n int height = getMaxHeight(restrictions[i-1], restrictions[i]);\n //cout << "[" << restrictions[i-1][0] << "," << restrictions[i-1][1]<< "] - " \n // << "[" << restrictions[i][0] << "," << restrictions[i][1]<< "] = " \n // << height << endl;\n maxHeight = max(maxHeight, height);\n \n }\n // cout << endl;\n return maxHeight;\n }\n};\n```\n\nThe following example are the debug information:\n\n**Example One:**\n```\n[[1,0],[2,1],[4,1],[5,4]]\n\n//from left to right\n[1,0] - [2,1] = 1\n[2,1] - [4,1] = 2\n[4,1] - [5,2] = 2 // <-- [5,4] changes to [5,2]\n\n//from right to left\n[4,1] - [5,2] = 2\n[2,1] - [4,1] = 2\n[1,0] - [2,1] = 1\n```\n\n**Example Two**\n\n```\n[[1,0],[2,4],[3,2],[4,0],[5,3],[6,2],[7,3],[8,5],[9,0],[10,0],[10,9]]\n\n//from left to right\n[1,0] - [2,1] = 1 // <-- [2,4] changed to [2,1]\n[2,1] - [3,2] = 2\n[3,1] - [4,0] = 1 // <-- [3,2] changes to [3,1]\n[4,0] - [5,1] = 1 // <-- [5,3] changes to [5,1]\n[5,1] - [6,2] = 2\n[6,2] - [7,3] = 3\n[7,3] - [8,4] = 4 // <-- [8,5] changes to [8,4]\n[8,1] - [9,0] = 1 // <-- [8,4] changes to [8,1]\n[9,0] - [10,0] = 0\n[10,0] - [10,0] = 0\n\n\n//from right to left\n[10,0] - [10,0] = 0\n[9,0] - [10,0] = 0\n[8,1] - [9,0] = 1\n[7,2] - [8,1] = 2 // <-- [7,3] changes to [7,2]\n[6,2] - [7,2] = 2 \n[5,1] - [6,2] = 2\n[4,0] - [5,1] = 1\n[3,1] - [4,0] = 1\n[2,1] - [3,1] = 1\n[1,0] - [2,1] = 1\n``` | 2 | 0 | [] | 1 |
maximum-building-height | My solution with thinking progress | my-solution-with-thinking-progress-by-me-icgf | Intuition\n Describe your first thoughts on how to solve this problem. \n- We want to build the highest building, but there are restrictions. So, we want to "ut | mercedes | NORMAL | 2024-04-27T09:11:57.396594+00:00 | 2024-04-27T09:11:57.396620+00:00 | 49 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- We want to build the highest building, but there are restrictions. So, we want to "utilize" each restriction to its maximum.\n- That is, for each restricted buildings, we try to make it as tall as possible.\n- We iterate from left. We only consider buildings with restrictions. Because, if we can decide the height of restricted buildings, we can deduct height of other buildings in their interval.\n- From left to right, each restricted building should satisfy:\n - Height less than or equal to its restriction;\n - Its left building can "reach" it, since only 1 height adjustment per building.\n \n- But what if we get too high, and cannot reduce the height in time to the second building\'s restriction? \n- That\'s what we do in the second pass. We amend each bulding\'s height by its next building. We just did the same thing, but by its previous building, in the first pass.\n\nIt\'s like a multipass compiler. Compilers do a little thing in each pass, finally output the program. In each pass, we get a little more information, hence the problem becomes easier too.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIterate the array 3 times. \n- First, only consider each restricted building\'s left constrain.\n- Second, only consider each restricted building\'s right constrain.\n- With each restricted building\'s height decided, we get answer through last iteration.\n\n\n# Code\n```\nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& restrictions) {\n if (restrictions.size() == 0)return n - 1;\n\n sort(restrictions.begin(), restrictions.end(), [](auto&& x, auto&& y) {return x[0] < y[0]; });\n\n int curId = 1;\n int curHeight = 0;\n\n // First pass, only consider left buildings.\n for (auto&& x : restrictions) {\n x[1] = min(x[1], x[0] - curId + curHeight);\n curId = x[0];\n curHeight = x[1];\n }\n\n // Second pass, only consider rights buildings\n for (int i = restrictions.size() - 2; i >= 0; i--) {\n restrictions[i][1] = min(restrictions[i][1], restrictions[i + 1][1] + restrictions[i + 1][0] - restrictions[i][0]);\n }\n \n // Get answer. The last building is the special case since no restriction on its right side.\n auto res = n - restrictions[restrictions.size() - 1][0] + restrictions[restrictions.size() - 1][1];\n curId = 1;\n curHeight = 0;\n for (auto&& x : restrictions) {\n // Given two restricted building\'s height, what\'s the maximum building height in their intervals? \n // First, we should compensate two building\'s height difference. The remained buildings can be built higher.\n int steps = x[0] - curId - abs(x[1] - curHeight);\n int higher = max(x[1], curHeight);\n // Remember to step down if we step up. Hence divide by 2.\n res = max(res, higher + steps / 2);\n curId = x[0];\n curHeight = x[1];\n }\n\n return res;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
maximum-building-height | Beats 100% C++ 2 Passes | beats-100-c-2-passes-by-tangd6-bket | First, notice that starting from the back, there is a fixed limit. In between this value and the value in front of it, there is only a certain amount of space. | tangd6 | NORMAL | 2024-01-24T02:52:27.575933+00:00 | 2024-01-24T02:52:27.575960+00:00 | 308 | false | First, notice that starting from the back, there is a fixed limit. In between this value and the value in front of it, there is only a certain amount of space. Thus, the maximum the previous value can be is actually LIMIT + DISTANCE since any higher than that, it will not be able to \'come back down\'.\n\nSo, I created a lim array which keeps track of this \'pseudo-min\' for each value.\n\nThen, I iterate from the beginning, keeping track of the current height I am at. The next height will just be the minimum of:\n- the maximum distance I can reach from current height\n- the the pseudo-constraint\n- the real constraint\nThat\'s it. Keep track of these and you should be successful.\n\nOf course, there\'s also the case of \'what is the max height I can reach in between if we start at height x and have to reach height y\'. The formula is just `LL mheight = y + (dist-(y-x))/2;`. Basically, the distance to make the heights equal, then you\'ll have some distance left over, so just divide it by 2 to go up and down.\n\n# Code\n```\nclass Solution {\npublic:\n #define LL long long\n static const int mx = (int)1e5 + 10;\n LL lim[mx];\n int maxBuilding(int n, vector<vector<int>>& rest) {\n LL sz = rest.size();\n if (sz == 0) {\n return n-1;\n }\n sort(rest.begin(), rest.end());\n lim[sz] = INT_MAX;\n for (int i = sz-1; i >= 0; i--) {\n LL diff = i != 0 ? rest[i][0] - rest[i-1][0] : rest[i][0];\n LL tmp = min(lim[i+1], (LL)rest[i][1]);\n lim[i] = tmp + diff;\n }\n LL run = 0;\n LL prev = 1;\n LL ans = 0;\n for (int i = 0; i < rest.size(); i++) {\n LL dist = rest[i][0] - prev;\n LL future = min({dist + run, lim[i+1], (LL)rest[i][1]});\n LL x = run, y = future;\n if (x > y) swap(x, y);\n LL mheight = y + (dist-(y-x))/2;\n run = future;\n ans = max(ans, run);\n ans = max(ans, mheight);\n prev = rest[i][0];\n }\n ans = max(ans, n-prev+run);\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
maximum-building-height | Sorting and Two Passes in Python | sorting-and-two-passes-in-python-by-meta-ru9n | Approach\n Describe your approach to solving the problem. \nThe first step is to sort the restrictions according to their positions. \nThe first pass begins fro | metaphysicalist | NORMAL | 2023-04-18T05:10:49.212506+00:00 | 2023-04-18T05:10:49.212547+00:00 | 151 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nThe first step is to sort the restrictions according to their positions. \nThe first pass begins from the rightmost to the leftmost for setting new height restriction of i according to the height restriction of its right parter (i+1).\nThe second pass begins from the leftmost to the rightmost for finding the answer. The maximum height between restrictions i and i+1 is determined by the function `max_point()` in my implmenetation. A new height restrictions to the i+1 building will also be updated at the same time. \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nSorting: $$O(n \\log n)$$\nTwo passes: $$O(n)$$ \n$$n$$ is the length of `restrictions`\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$ in place. \n\n# Code\n```\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n def max_point(x1, h1, x2, h2):\n w, d = x2 - x1, abs(h2 - h1)\n h = w - ((max(0, w-d) + 1) // 2)\n return min(h1, h2) + h\n\n restrictions = sorted(restrictions + [[1, 0], [n, n+1]])\n for i in range(len(restrictions) - 2, -1, -1):\n if restrictions[i][1] > restrictions[i+1][1]:\n w = restrictions[i+1][0] - restrictions[i][0]\n restrictions[i][1] = min(restrictions[i][1], restrictions[i+1][1] + w)\n ans = 0\n for i in range(len(restrictions)-1):\n h = max_point(*restrictions[i], *restrictions[i+1])\n restrictions[i+1][1] = min(restrictions[i+1][1], h)\n ans = max(ans, h)\n return ans\n\n \n``` | 1 | 0 | ['Greedy', 'Sorting', 'Python3'] | 0 |
maximum-building-height | Clean solution with detailed explanation and comments | clean-solution-with-detailed-explanation-j4vv | Intuition\nYou cannot iterate on each step, because that will be too many. Need think of a solution that involves the restrictions only.\nThe height at each res | sujoychatts | NORMAL | 2023-03-14T17:51:14.149791+00:00 | 2023-03-14T17:51:14.149838+00:00 | 55 | false | # Intuition\nYou cannot iterate on each step, because that will be too many. Need think of a solution that involves the restrictions only.\nThe height at each restriction point is determined not only by its own restriction but also by the restrictions on its left and right. That is because you can increment / decrement height by only one unit per distance unit.\n\n# Approach\nCalculate from both left to right and right to left to understand the real restrictions associated with the two adjescent restrictions.\nOnce that is foind, there is one more catch, withing the distance that is between the two buildings, it is possible to use the extra distance available (than the distance it will take to reach from one building height to the next building hight) to maximise the buiding height in between.\n\n# Complexity\n- Time complexity:\nO(r log r), where r is the number of buildings with height restrictions.\n\n- Space complexity:\nO(r), where r is the number of buildings with height restrictions.\n\n# Code\n```\n/**\n * @param {number} n\n * @param {number[][]} restrictions\n * @return {number}\n */\nvar maxBuilding = function(n, restrictions) {\n // Add edge restrictions\n restrictions.push([1, 0]);\n restrictions.push([n, n - 1]);\n\n // Sort by distance from start (id)\n restrictions.sort(([v1], [v2]) => v1 - v2);\n\n // If you went incrementing from left to right, what is the height you can set for each point,\n // considering its own restriction.\n for(let i = 1; i < restrictions.length; i++) {\n const distance = restrictions[i][0] - restrictions[i - 1][0];\n const heightWithOneStepIncrement = distance + restrictions[i-1][1];\n restrictions[i][1] = Math.min(restrictions[i][1], heightWithOneStepIncrement)\n }\n \n // If you went incremending from right to left, what is the height you can set for each point,\n // considering its own restriction.\n for(let i = restrictions.length - 2; i >=0; i--) {\n const distance = restrictions[i+1][0] - restrictions[i][0];\n const heightWithOneStepIncrement = distance + restrictions[i+ 1][1];\n restrictions[i][1] = Math.min(restrictions[i][1], heightWithOneStepIncrement)\n }\n\n let max = 0;\n for(let i = 0; i < restrictions.length - 1; i++) {\n const distance = restrictions[i+1][0] - restrictions[i][0]\n const heightDiff = Math.abs(restrictions[i+1][1] - restrictions[i][1])\n const maxHeight = Math.max(restrictions[i+1][1], restrictions[i][1]);\n\n const leeway = distance - heightDiff - 1;\n const midHeightBuffer = Math.ceil(leeway / 2)\n max = Math.max(max, maxHeight + midHeightBuffer)\n }\n return max\n};\n``` | 1 | 0 | ['JavaScript'] | 0 |
maximum-building-height | Simple Java Solution | simple-java-solution-by-aayushkumar20-s9ag | \n// Maximum Building Height\n// Leetcode: https://leetcode.com/problems/maximum-building-height/\n\nclass Solution {\n public int maxBuilding(int n, int[][] | aayushkumar20 | NORMAL | 2022-10-10T14:50:55.782876+00:00 | 2022-10-10T14:50:55.782969+00:00 | 232 | false | ```\n// Maximum Building Height\n// Leetcode: https://leetcode.com/problems/maximum-building-height/\n\nclass Solution {\n public int maxBuilding(int n, int[][] restrictions) \n {\n int[][] arr = new int[restrictions.length + 2][2];\n arr[0][0] = 1;\n arr[0][1] = 0;\n arr[arr.length - 1][0] = n;\n arr[arr.length - 1][1] = n - 1;\n for (int i = 1; i < arr.length - 1; i++)\n {\n arr[i][0] = restrictions[i - 1][0];\n arr[i][1] = restrictions[i - 1][1];\n }\n Arrays.sort(arr, (a, b) -> a[0] - b[0]);\n for (int i = 1; i < arr.length; i++)\n {\n arr[i][1] = Math.min(arr[i][1], arr[i - 1][1] + arr[i][0] - arr[i - 1][0]);\n }\n for (int i = arr.length - 2; i >= 0; i--)\n {\n arr[i][1] = Math.min(arr[i][1], arr[i + 1][1] + arr[i + 1][0] - arr[i][0]);\n }\n int max = 0;\n for (int i = 1; i < arr.length; i++)\n {\n max = Math.max(max, (arr[i][1] + arr[i - 1][1] + arr[i][0] - arr[i - 1][0]) / 2);\n }\n return max; \n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
maximum-building-height | Prefix + suffix Array | prefix-suffix-array-by-diyora13-o5pg | \nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& a) \n {\n a.push_back({1,0});\n a.push_back({n,n-1});\n int | diyora13 | NORMAL | 2022-06-08T07:10:11.899414+00:00 | 2022-06-08T07:10:11.899454+00:00 | 405 | false | ```\nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& a) \n {\n a.push_back({1,0});\n a.push_back({n,n-1});\n int m=a.size();\n if(!m) return n-1;\n sort(a.begin(),a.end());\n int mn[m];\n for(int i=0;i<m;i++)\n mn[i]=INT_MAX;\n mn[0]=min(a[0][0]-1,a[0][1]);\n int h=mn[0];\n for(int i=1;i<m;i++)\n {\n h+=a[i][0]-a[i-1][0];\n h=min(h,a[i][1]);\n mn[i]=min(mn[i],h);\n }\n \n h=mn[m-1];\n for(int i=m-2;i>=0;i--)\n {\n h+=a[i+1][0]-a[i][0];\n h=min(h,a[i][1]);\n mn[i]=min(mn[i],h);\n }\n \n int ans=0;\n for(int i=1;i<m;i++)\n ans=max(ans,max(mn[i],mn[i-1])+((a[i][0]-a[i-1][0]-1)-abs(mn[i]-mn[i-1])+1)/2);\n\n return ans;\n }\n};\n``` | 1 | 0 | ['Greedy', 'C', 'Sorting', 'C++'] | 0 |
maximum-building-height | Faster than 100% || C++ | faster-than-100-c-by-i_see_you-mvod | \nclass Solution {\npublic:\n /*\n Hint: \n 1. Dp\n 2. We know that the 1st building is of height 0, and some other buildings ha | i_see_you | NORMAL | 2022-05-05T11:47:33.633042+00:00 | 2022-05-05T11:47:53.113897+00:00 | 201 | false | ```\nclass Solution {\npublic:\n /*\n Hint: \n 1. Dp\n 2. We know that the 1st building is of height 0, and some other buildings have some restriction on their heights\n 3. If we go from left to right, we will notice every left restiction height can affect to it\'s just right rescriction building, example\n [positoin = 5, maxHeight = 2] [postion = 10, maxHeight = 16]\n here although the 2nd building has a high hight limit (16) it is not really possible to do that because it is bound by it\'s\n previous one so the postion 10 can at max have a height of\n min(16, 2 + (10 - 5)) = 7\n 4. Same relation holds for building from right to left\n 5. After we have figured out the max height possible for all buildings \n 6. We also need to think about cases like this \n [position = 2, maxHeight = 1] [position = 8, maxHeight = 3]\n so between these two rescrictoin, we can start with [height 1] from [postion 2] then start increasing height as much as \n [height 5] on [position 6] then decrease the height to meet the constraint height of 3 at postion 8.\n And the formula for that is \n between two rescriction (i, j) [remember i and j are adjacent resctirctions]\n \n \n max_height = max(max_height_possible[i], max_height_possible[j]) + ((i - j - 1) - abs(max_height_possible[i] - max_height_possible[j]) + 1) / 2;\n */\n \n #define inf 0x3f3f3f3f\n int max_height_possible[100002];\n int maxBuilding(int n, vector<vector<int>>& restrictionsLimit) {\n vector <pair<int, int>> restrictions;\n restrictions.push_back({1, 0});\n for (int i = 0; i < restrictionsLimit.size(); i++) restrictions.push_back({restrictionsLimit[i][0], restrictionsLimit[i][1]});\n \n sort(restrictions.begin(), restrictions.end(), [](pair<int, int> i, pair <int, int> j) {\n return i.first < j.first; \n });\n \n if (restrictions.back().first != n) restrictions.push_back({n, inf});\n int len = restrictions.size();\n \n for (int i = 1; i < len; i++) {\n int difference = restrictions[i].first - restrictions[i - 1].first;\n max_height_possible[i] = min(restrictions[i].second, max_height_possible[i - 1] + difference);\n }\n \n int max_building_height = 0;\n for (int i = len - 2; i >= 0; i--) {\n int difference = restrictions[i + 1].first - restrictions[i].first;\n max_height_possible[i] = min(max_height_possible[i], max_height_possible[i + 1] + difference);\n \n difference = (difference - 1) - abs(max_height_possible[i + 1] - max_height_possible[i]);\n max_building_height = max(max_building_height, max(max_height_possible[i + 1], max_height_possible[i]) + (difference + 1) / 2);\n }\n \n return max_building_height;\n }\n};\n``` | 1 | 0 | [] | 0 |
maximum-building-height | Javascript explained | javascript-explained-by-theesoteric-pd5n | \n/**\n * @param {number} n\n * @param {number[][]} restrictions\n * @return {number}\n */\nvar maxBuilding = function(n, restrictions) {\n let maxHeight=0;\ | theesoteric | NORMAL | 2022-02-13T17:55:16.053560+00:00 | 2022-02-13T17:55:16.053604+00:00 | 150 | false | ```\n/**\n * @param {number} n\n * @param {number[][]} restrictions\n * @return {number}\n */\nvar maxBuilding = function(n, restrictions) {\n let maxHeight=0;\n restrictions.push([1,0]);//Push extra restriction as 0 for 1\n restrictions.push([n,n-1]);//Push extra restrition as n-1 for n\n restrictions.sort(function(a,b){return a[0]-b[0]});\n //Propogate from left to right to tighten the restriction: Check building restriction can be furhter tightened due to the left side building restriction. \n for(let i=1;i<restrictions.length;i++){\n restrictions[i][1] = Math.min(restrictions[i][1], (restrictions[i][0]-restrictions[i-1][0])+restrictions[i-1][1]);\n }\n //Propogate from right to left to tighten the restriction: Check building restriction can be furhter tightened due to the right side building restriction. \n for(let i=restrictions.length-2;i>=0;i--){\n restrictions[i][1] = Math.min(restrictions[i][1], (restrictions[i+1][0]-restrictions[i][0])+restrictions[i+1][1]);\n }\n let max=0;\n for(let i=0;i<restrictions.length-1;i++){\n let leftHeight = restrictions[i][1];\n let rightHeight = restrictions[i+1][1];\n let distance = restrictions[i+1][0]-restrictions[i][0]-1;//Number of cities between ith and i+1th city, excluding these cities\n let hightDiff = Math.abs(restrictions[i+1][1]-restrictions[i][1]);\n let middleHeight = Math.max(leftHeight,rightHeight)+Math.ceil((distance-hightDiff)/2);\n max = Math.max(max,middleHeight);\n }\n return max;\n};\n``` | 1 | 0 | ['JavaScript'] | 0 |
maximum-building-height | Python O(m log m) Solution with Clear Explanation and Analysis | python-om-log-m-solution-with-clear-expl-cgo4 | In the begining, the first solution we may think about is: \n* compute every buildings height and get the maximum of them\n\nBut this will give you TLE, so we m | taranthemonk | NORMAL | 2022-01-19T11:59:00.694001+00:00 | 2022-01-19T11:59:28.067056+00:00 | 167 | false | In the begining, the first solution we may think about is: \n* compute every buildings height and get the maximum of them\n\nBut this will give you TLE, so we must ask ourselves, do I really need to know the height for all buildings to know what is the maximum height I can get?\n\nLet me try to explain the analysis process:\n1. Given two buildings `(i1, h1)` and `(i2, h2)`, what is the maximum height I can get inclusively between them?\n\t1.1 Suppose `i1 < i2`, then we can increase `x` height from `h1` and decrease `y` height to get `h2`:\n\t1.2 This gives us: `h1 + x - y = h2` and `x + y = i2 - i1`.\n\t1.3 Solve 1.2, we get: `x = ((i2 - i1) + (h2 - h1)) / 2`.\n\n2. What if the `x` we get from solving 1 is a float?\n\t2.1 This means, we incresed height for `bottom(x)` and then increased `x - bottom(x)`.\n\t2.2 After that, we decreased height for `y-bottom(y)` and then decreased `y`.\n\t2.3 Notice that `(x - bottom(x)) + (y-bottom(y)) = 1`, meaning these two actions happened abstractly between two discrete buildings which has a same height. So the actuall increase is `bottom(x)`\n\t\n3. If I can solve problem 1, then which buildings\' height should be fixed to perform the solution for problem 1?\n\t3.1 The restricted buildings! Their height is constrained by each other.\n\nSo now the solution is simple:\n1. We compute the height for every restricted buildings.\n2. Between two restricted buildings, we compute the maximum height we can get inclusively between them.\n\nBelow is an implementation with Python:\n```python\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n # no restriction\n if len(restrictions) == 0:\n return n - 1\n \n # manually add restrictions for the first and last buildings\n restrictions.append([1, 0])\n restrictions.sort(key=lambda x: x[0])\n if restrictions[-1][0] != n:\n restrictions.append([n, float("+inf")])\n \n # get valid height for restricted buildings\n m = len(restrictions)\n for i in range(1, m):\n prev_idx, prev_height = restrictions[i-1]\n idx, height = restrictions[i]\n height = min(height, prev_height + (idx - prev_idx))\n restrictions[i] = [idx, height]\n \n for i in range(m-2, 0, -1):\n next_idx, next_height = restrictions[i+1]\n idx, height = restrictions[i]\n height = min(height, next_height + (next_idx - idx))\n restrictions[i] = [idx, height]\n \n # find max height between every two restricted buildings\n ret = 0\n prev_idx = restrictions[0][0]\n prev_height = restrictions[0][1]\n for idx, height in restrictions:\n x = int(((idx - prev_idx) + (height - prev_height)) / 2)\n ret = max(ret, prev_height + x)\n prev_idx = idx\n prev_height = height\n \n return ret\n```\n\nTime complexity: suppose the `restrictions` array has `m` elements, we did 3 transverse and 1 sort on it, so `O(mlogm)`.\n\n | 1 | 0 | ['Sorting'] | 0 |
maximum-building-height | Simple Stack Solution, O(N) after sorting, O(1) space | simple-stack-solution-on-after-sorting-o-s91q | Each restriction at (x,y) means restrictions at (x\xB1i, y+i) for all buildings, that is, each origin restriction is a vertical V shape angle. We will find the | slo | NORMAL | 2021-05-04T09:44:31.474167+00:00 | 2021-05-04T09:56:13.250121+00:00 | 387 | false | Each restriction at `(x,y)` means restrictions at `(x\xB1i, y+i)` for all buildings, that is, each origin restriction is a vertical `V` shape angle. We will find the highest point on lower boundary of all `V`s.\nYou may reuse the `restrictions` argument for O(1) space.\n```c++\n/*\nn = 5, restrictions = [[2,1],[4,1]]\n\n /\n / \\ /\n / \\ / \\ /\n(1,0) (2,1) (4,1)\n*/\n\n\nusing pii = pair<int, int>;\n#define x first\n#define y second\n\nbool contain(pii a, pii b) {\n return b.y >= a.y + abs(b.x - a.x);\n}\n\n// return the height of intersection, a.x < b.x\nint calc(pii a, pii b) {\n int x = (b.y + b.x + a.x - a.y) / 2;\n return x - a.x + a.y;\n}\n\nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& rs) {\n sort(rs.begin(), rs.end(), [](auto& x, auto& y) { return x[0] < y[0]; });\n vector<pii> st;\n st.push_back({1, 0});\n for (auto& r: rs) {\n pii p{r[0], r[1]};\n if (contain(st.back(), p)) continue;\n while (contain(p, st.back())) st.pop_back();\n st.push_back(p);\n }\n int res = n - st.back().x + st.back().y;\n for (int i = 1; i < st.size(); ++i)\n res = max(res, calc(st[i - 1], st[i]));\n return res;\n }\n};\n``` | 1 | 0 | [] | 0 |
maximum-building-height | 67% : Python | 67-python-by-tuhinnn_py-cwuf | We initially sort the restrictions array just to keep the building indices in ascending order. Now suppose, the restrictions array looks something like this\nA | tuhinnn_py | NORMAL | 2021-05-02T18:10:14.678263+00:00 | 2021-05-02T18:10:14.678320+00:00 | 202 | false | ***We initially sort the restrictions array just to keep the building indices in ascending order. Now suppose, the restrictions array looks something like this\nA = [...., [id1, h1], [id2, h2], ...] which suggests, you have two buildings restricted by heights h1 and h2 and spaced by id2 - id1\nHere\'s my claim, Building 1 with a building id id1, can have a maximum height of h2 + id2 - id1 and a minimum height of h2 - (id2 - id1). Think about it, In case they are adjacent, implying id2 - id1 = 1,\nh1 can be any of the following [h2 + 1, h2, h2 - 1] with a maximum height of h2 + 1 and minimum height of h2 - 1. Thus if h1 > h2 + 1 we trim h1. We don\'t trim it in case it\'s shorter because that would mean we are tampering with the restrictions.\nThis trimming takes place twice. Once we traverse the array from the left and trim the current building\'s height(if necessary) keeping in mind the next building. \nSimilarly, we traverse the array from right to left again to trim the current building based on a past building. \nNow, we do have some math involved in figuring out the maximum height between h1 and h2.\nLet\'s suppose the maximum height is y and it\'s x distance apart from h1. (note that the building id would be id(h1) + x)\nSo we have two equations, \ni) y - h1 = x\nii) y - h2 = h2 - h1 - x\nWe solve for y and x over all adjacent pairs of buildings and keep track of the maximum.***\n```\nclass Solution:\n def maxBuilding(self, n: int, A: List[List[int]]) -> int:\n A.sort()\n A = [[1, 0]] + A\n N = len(A)\n for i in range(N - 1):\n if abs(A[i][1] - A[i+1][1]) > abs(A[i][0] - A[i+1][0]):\n A[i+1][1] = min(A[i+1][1], A[i][1] + A[i+1][0] - A[i][0])\n for i in range(N - 1, 0, -1):\n if abs(A[i][1] - A[i-1][1]) > abs(A[i][0] - A[i-1][0]):\n A[i-1][1] = min(A[i-1][1], A[i][1] + A[i][0] - A[i-1][0])\n res = n - A[-1][0] + A[-1][1]\n for i in range(N - 1):\n res = max(res, (A[i+1][0] - A[i][0] + A[i][1] + A[i+1][1]) // 2)\n return res\n``` | 1 | 0 | [] | 0 |
maximum-building-height | [Golang] Go two-pass solution | golang-go-two-pass-solution-by-grokus-zs4n | ```\nfunc maxBuilding(n int, a [][]int) int {\n\ta = append(a, [][]int{{1, 0}, {n, n - 1}}...)\n\tsort.Slice(a, func(i, j int) bool { return a[i][0] < a[j][0] } | grokus | NORMAL | 2021-04-25T18:56:19.044426+00:00 | 2021-04-25T18:56:36.702058+00:00 | 63 | false | ```\nfunc maxBuilding(n int, a [][]int) int {\n\ta = append(a, [][]int{{1, 0}, {n, n - 1}}...)\n\tsort.Slice(a, func(i, j int) bool { return a[i][0] < a[j][0] })\n\tres := 0\n\tfor i := len(a) - 2; i >= 0; i-- {\n\t\ta[i][1] = min(a[i][1], a[i+1][1]+a[i+1][0]-a[i][0])\n\t}\n\tfor i := 1; i < len(a); i++ {\n\t\ta[i][1] = min(a[i][1], a[i-1][1]+a[i][0]-a[i-1][0])\n\t\tx := a[i][0] - a[i-1][0] + abs(a[i][1]-a[i-1][1])\n\t\tres = max(res, x/2+min(a[i-1][1], a[i][1]))\n\t}\n\treturn res\n}\n\nfunc abs(a int) int {\n\tif a < 0 {\n\t\treturn -a\n\t}\n\treturn a\n}\n\nfunc max(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n | 1 | 0 | [] | 0 |
maximum-building-height | Simple java solution with explanation comments - Time: O(k log k), Space: O(1) | simple-java-solution-with-explanation-co-iwgj | Same approach as this post by Janevans\n\n\nclass Solution {\n public int maxBuilding(int n, int[][] restrictions) {\n // If there are no restrictions | hss15 | NORMAL | 2021-04-25T10:56:55.636663+00:00 | 2021-04-25T11:00:21.195266+00:00 | 180 | false | Same approach as [this post](https://leetcode.com/problems/maximum-building-height/discuss/1175058/Java-O(1)-space-O(klogk)-time-with-comments) by [Janevans](https://leetcode.com/janevans/)\n\n```\nclass Solution {\n public int maxBuilding(int n, int[][] restrictions) {\n // If there are no restrictions, we will just keep increasing the height of next building till end \n // and height of last building will be n - 1\n if (restrictions.length == 0)\n return n - 1;\n \n // sort the restrictions as per index\n Arrays.sort(restrictions, new Comparator<int[]>(){\n public int compare(int[] a, int[] v) {\n return Integer.compare(a[0], v[0]);\n }\n });\n \n int rLen = restrictions.length;\n \n // We might not always be able to reach the original restriction height at any given index.\n // Eg: [[3,5]]. Since height of building at id=1 will always be 0, height of building at id=3 can not be more than 2.\n // It can be less than 2 depending upon the limit of building on it\'s right.\n // Eg: [[3,5],[4,0]]. Here the height of duilding at id=3 will be 1 since building at id=4 have upper limit of height 0.\n \n // Update the limit while maintaining the restrictions and moving forward\n int pIndex = 1;\n int pHeight = 0;\n for(int[] res : restrictions) {\n res[1] = Math.min(res[1], pHeight + res[0] - pIndex);\n pIndex = res[0];\n pHeight = res[1];\n }\n \n // Update the limit while maintaining the restrictions and moving backward\n pIndex = n;\n pHeight = n - 1;\n for(int i = rLen - 1; i >= 0; i--) {\n restrictions[i][1] = Math.min(restrictions[i][1], pHeight + pIndex - restrictions[i][0]);\n pHeight = restrictions[i][1];\n pIndex = restrictions[i][0];\n }\n \n // Calculate the maximum height between 2 restriction and compare it with global maximum.\n int maxHeight = 1;\n pIndex = 1;\n pHeight = 0;\n for(int[] restriction : restrictions) {\n int hDiff = Math.abs(pHeight - restriction[1]);\n int iDiff = restriction[0] - pIndex;\n int extraHeight = Math.abs((iDiff - hDiff) / 2);\n \n maxHeight = Math.max(maxHeight, Math.max(pHeight, restriction[1]) + extraHeight);\n \n pIndex = restriction[0];\n pHeight = restriction[1];\n }\n \n // If there is no restriction on height of last building, take it to max as much as possible\n if (restrictions[rLen - 1][0] != n) {\n maxHeight = Math.max(maxHeight, restrictions[rLen - 1][1] + n - restrictions[rLen - 1][0]);\n }\n \n return maxHeight;\n }\n}\n``` | 1 | 0 | [] | 0 |
maximum-building-height | 1840. Maximum Building Height | 1840-maximum-building-height-by-g8xd0qpq-8f6q | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | G8xd0QPqTy | NORMAL | 2025-01-15T13:50:46.649333+00:00 | 2025-01-15T13:50:46.649333+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 maxBuilding(int n, vector<vector<int>>& restrictions) {
restrictions.push_back({1, 0});
restrictions.push_back({n, n - 1});
sort(restrictions.begin(), restrictions.end());
int len = restrictions.size();
for (int idx = 1; idx < len; ++idx) {
int currPos = restrictions[idx][0], prevPos = restrictions[idx - 1][0];
int currHeight = restrictions[idx][1], prevHeight = restrictions[idx - 1][1];
restrictions[idx][1] = min(currHeight, prevHeight + currPos - prevPos);
}
for (int idx = len - 2; idx >= 0; --idx) {
int currPos = restrictions[idx][0], nextPos = restrictions[idx + 1][0];
int currHeight = restrictions[idx][1], nextHeight = restrictions[idx + 1][1];
restrictions[idx][1] = min(currHeight, nextHeight + nextPos - currPos);
}
int maxPossibleHeight = 0;
for (int idx = 1; idx < len; ++idx) {
int leftPos = restrictions[idx - 1][0], rightPos = restrictions[idx][0];
int leftHeight = restrictions[idx - 1][1], rightHeight = restrictions[idx][1];
maxPossibleHeight = max(maxPossibleHeight, max(leftHeight, rightHeight) + (rightPos - leftPos - abs(leftHeight - rightHeight)) / 2);
}
return maxPossibleHeight;
}
};
``` | 0 | 0 | ['C++'] | 0 |
maximum-building-height | Simple 3 pass solutions, beats all | simple-3-pass-solutions-beats-all-by-sup-nyvc | 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 | supercmmetry | NORMAL | 2024-11-07T14:15:41.535479+00:00 | 2024-11-07T14:15:41.535505+00:00 | 1 | 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```rust []\nuse std::cmp::{min, max};\n\nimpl Solution {\n pub fn max_building(n: i32, mut arr: Vec<Vec<i32>>) -> i32 {\n arr.sort_unstable();\n arr.insert(0, vec![1, 0]);\n \n if arr.last().unwrap()[0] != n {\n arr.push(vec![n, n - 1]);\n }\n\n for x in arr.iter_mut() {\n x[1] = min(x[1], x[0] - 1);\n }\n\n let n: usize = arr.len();\n\n for i in 0..n-1 {\n arr[i + 1][1] = min(arr[i + 1][1], arr[i][1] + arr[i + 1][0] - arr[i][0]);\n }\n\n for i in (0..n-1).rev() {\n arr[i][1] = min(arr[i][1], arr[i + 1][1] + arr[i + 1][0] - arr[i][0]);\n }\n\n let mut output: i32 = 0;\n\n for i in 0..n-1 {\n let a: i32 = min(arr[i][1], arr[i + 1][1]);\n let b: i32 = max(arr[i][1], arr[i + 1][1]);\n let c: i32 = arr[i + 1][0] - arr[i][0];\n\n output = max(output, (a + b + c) / 2);\n }\n\n output\n }\n}\n``` | 0 | 0 | ['Rust'] | 0 |
maximum-building-height | C++ beats 100% in 30ms | c-beats-100-in-30ms-by-ivangnilomedov-127o | Code\ncpp []\nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& restrictions) {\n // Step 1: Prepare and sort restrictions\n | ivangnilomedov | NORMAL | 2024-10-20T16:31:05.266293+00:00 | 2024-10-20T16:31:05.266330+00:00 | 4 | false | # Code\n```cpp []\nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& restrictions) {\n // Step 1: Prepare and sort restrictions\n vector<pair<int, int>> id_restr(restrictions.size() + 1);\n transform(restrictions.begin(), restrictions.end(), id_restr.begin() + 1,\n [](const vector<int>& r) { return make_pair(r[0] - 1, r[1]); });\n --n; // Adjust to 0-based indexing\n sort(id_restr.begin(), id_restr.end());\n\n // Step 2: Filter out redundant restrictions\n vector<bool> alive(id_restr.size(), true);\n // Forward pass: eliminate restrictions that are higher than possible\n for (int last_alive = 0, i = 1; i < id_restr.size(); ++i) {\n int max_possible_height =\n id_restr[last_alive].second + id_restr[i].first - id_restr[last_alive].first;\n alive[i] = id_restr[i].second < max_possible_height;\n if (alive[i]) last_alive = i;\n }\n // Backward pass: further eliminate restrictions\n for (int last_alive = id_restr.size() - 1, i = id_restr.size() - 2; i >= 0; --i) {\n int max_possible_height =\n id_restr[last_alive].second + id_restr[last_alive].first - id_restr[i].first;\n alive[i] = alive[i] && id_restr[i].second < max_possible_height;\n if (alive[i]) last_alive = i;\n }\n // Compact the id_restr vector to keep only relevant restrictions\n int alive_len = 0;\n for (int i = 0; i < id_restr.size(); ++i) {\n if (alive[i]) {\n if (alive_len < i) swap(id_restr[alive_len], id_restr[i]);\n ++alive_len;\n }\n }\n id_restr.resize(alive_len);\n\n // Step 3: Find the maximum height\n // Initialize with the height possible at the last building\n long long res =\n static_cast<long long>(id_restr.back().second) + n - id_restr.back().first;\n\n // Check between each pair of restrictions\n for (int i = 0; i < id_restr.size() - 1; ++i) {\n auto [id, restr] = id_restr[i];\n res = max<long long>(res, restr);\n auto [next_index, next_res] = id_restr[i + 1];\n // Check max height between i and next restriction\n long long peak_height =\n (static_cast<long long>(restr) + next_index - id - next_res) / 2 + next_res;\n res = max(res, peak_height);\n }\n\n return res;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-building-height | 1840. Maximum Building Height.cpp | 1840-maximum-building-heightcpp-by-20202-9lpq | Code\n\nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& restrictions) {\n restrictions.push_back({1, 0});\n restriction | 202021ganesh | NORMAL | 2024-10-17T10:07:19.077233+00:00 | 2024-10-17T10:07:19.077260+00:00 | 0 | false | **Code**\n```\nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& restrictions) {\n restrictions.push_back({1, 0});\n restrictions.push_back({n, n-1}); \n sort(restrictions.begin(), restrictions.end()); \n for (int i = restrictions.size()-2; i >= 0; --i) {\n restrictions[i][1] = min(restrictions[i][1], restrictions[i+1][1] + restrictions[i+1][0] - restrictions[i][0]); \n } \n int ans = 0; \n for (int i = 1; i < restrictions.size(); ++i) {\n restrictions[i][1] = min(restrictions[i][1], restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0]); \n ans = max(ans, (restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0] + restrictions[i][1])/2); \n }\n return ans; \n }\n};\n``` | 0 | 0 | ['C'] | 0 |
maximum-building-height | optimized solution | optimized-solution-by-sbishnoi29-xpwu | 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 | sbishnoi29 | NORMAL | 2024-09-20T20:46:56.182835+00:00 | 2024-09-20T20:46:56.182859+00:00 | 3 | 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 int maxBuilding(int n, vector<vector<int>>& a) \n {\n a.push_back({1,0});\n a.push_back({n,n-1});\n int m=a.size();\n if(!m) return n-1;\n sort(a.begin(),a.end());\n int mn[m];\n for(int i=0;i<m;i++)\n mn[i]=INT_MAX;\n mn[0]=min(a[0][0]-1,a[0][1]);\n int h=mn[0];\n for(int i=1;i<m;i++)\n {\n h+=a[i][0]-a[i-1][0];\n h=min(h,a[i][1]);\n mn[i]=min(mn[i],h);\n }\n \n h=mn[m-1];\n for(int i=m-2;i>=0;i--)\n {\n h+=a[i+1][0]-a[i][0];\n h=min(h,a[i][1]);\n mn[i]=min(mn[i],h);\n }\n \n int ans=0;\n for(int i=1;i<m;i++)\n ans=max(ans,max(mn[i],mn[i-1])+((a[i][0]-a[i-1][0]-1)-abs(mn[i]-mn[i-1])+1)/2);\n\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-building-height | C++ | c-by-tinachien-l6gg | \nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& restrictions) {\n int ret;\n restrictions.push_back({1,0});\n | TinaChien | NORMAL | 2024-09-15T02:10:51.373213+00:00 | 2024-09-15T02:10:51.373231+00:00 | 0 | false | ```\nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& restrictions) {\n int ret;\n restrictions.push_back({1,0});\n sort(restrictions.begin(), restrictions.end());\n int m = restrictions.size();\n vector<int>pos(m);\n vector<int>height(m);\n vector<int>limit(m);\n\n height[0] = 0;\n for(int i = 0; i < m ;i++){\n pos[i] = restrictions[i][0];\n limit[i] = restrictions[i][1];\n }\n for(int i = 1; i < m; i++){\n height[i] = min(limit[i], height[i-1] + pos[i] - pos[i-1]);\n }\n for(int i = m-2; i >= 1; i--){\n height[i] = min(height[i], height[i+1] + pos[i+1] - pos[i]); \n }\n ret = 0;\n //h[i-1] + x = h[i] + y\n //p[i-1] + x = p[i] - y\n //2y = p[i] - p[i-1] - h[i] + h[i-1]\n for(int i = 1; i < m; i++){\n int y = (pos[i] - pos[i-1] - height[i] + height[i-1])/2;\n ret = max(ret, height[i] + y);\n }\n ret = max(ret, height[m-1] + n - pos[m-1]);\n return ret;\n }\n};\n``` | 0 | 0 | [] | 0 |
maximum-building-height | C++ 11 line | c-11-line-by-sanzenin_aria-crkv | 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 | sanzenin_aria | NORMAL | 2024-08-27T22:42:33.849594+00:00 | 2024-08-27T22:42:33.849618+00:00 | 0 | 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:\nO(nlogn)\n\n- Space complexity:\nO(1)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& rs) {\n rs.push_back(vector<int>{1,0});\n ranges::sort(rs);\n for(int i=1;i<rs.size();i++) rs[i][1] = min(rs[i][1], rs[i-1][1] + rs[i][0] - rs[i-1][0]);\n for(int i=rs.size()-1;i>0;i--) rs[i-1][1] = min(rs[i-1][1], rs[i][1] + rs[i][0] - rs[i-1][0]);\n int res = 0;\n for(int i = 0;i<rs.size()-1;i++){\n int i0 = rs[i][0], h0 = rs[i][1], i1= rs[i+1][0], h1 = rs[i+1][1];\n int dh = abs(h0-h1), di = i1-i0;\n res = max(res, (di+dh)/2 + min(h0, h1)); \n }\n return max(res, n - rs.back()[0] + rs.back()[1]);\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-building-height | Python 3: TC O(N log(N)), SC O(N): Sort plus Three Passes. Two Passes and SC O(log(N)) Possible | python-3-tc-on-logn-sc-on-sort-plus-thre-26k4 | Intuition\n\nThis is a hard problem to get the insight for.\n\n## Array-of-Limits Pattern in General\n\nThe usual pattern for this, trapping rain water, distrib | biggestchungus | NORMAL | 2024-07-08T20:47:06.566224+00:00 | 2024-07-08T20:47:06.566244+00:00 | 13 | false | # Intuition\n\nThis is a hard problem to get the insight for.\n\n## Array-of-Limits Pattern in General\n\nThe usual pattern for this, trapping rain water, distributing candies, etc. is to look at some index `i`\n* usually the value for `i` (this case height) has some limits\n* there\'s a left limit, from a restriction at index `l <= i`\n* and there\'s a right limit from a restriction at index `r >= i`\n* the max height can be computed from these two limits\n\nIn this case:\n* if we\'re limited by `l, lh` to the left\n* and `r, rh` to the right\n* then our max height is either\n * `min(lh, rh) + r-l`: we start at the lower one, and use the r-l increments we can do between l to r to get to a height `<= max(lh, rh)`\n * or maybe we can get higher: spend `max(lh, rh) - min(lh, rh)` of the `r-l` increments possible to bring the lower height up to the higher height, then make a pyramid shape going up and then down. What goes up must come down, so each upward increment must be met with a downward increment. So `(r-l-(max-min))//2` is the max height we can get on the interval\n\n## TC O(N log(N)), SC O(N): Basic: Cumulative from Right\n\nWe can make an array of cumulative limits to the right in `O(N)` time and `O(N)` space.\n\nThen we can process from the left\n* record a cumulative limit to the left\n* use the limit to the left and right as described above to compute the max height over every interval\n* return the max height we saw anywhere\n\n## TC O(N log(N)), SC O(N): Fancy: Cumulative In-Place\n\nSuppose we have two limits to the left:\n* `l1, l1h`\n* `l2, l2h`\n* in general, one of these is at least as restrictive as the other one\n* so we can replace the less restrictive one with the more restrictive one!\n\nThat means if we look at each `i, h` pair, if there\'s an earlier `i\', h\'` pair that imposes a harsher limit on the max height, then `i, h` doesn\'t matter - the height is limited to the left by the stricter limit anyway. So we can just set `h` to `h\' + i-i\'`, thereby replacing the `i, h` limit with the stricter earlier limit.\n\nThis lets us do the cumulative left-to-right limit in place.\n\nFollowing the same logic we can do a right-to-left pass to also include the cumulative most restrictive limit to the right, also in place with `O(1)` memory.\n\n**This lowers the space complexity to O(1) for the cumulative limits to left and right.**\n\n# Approach\n\nMostly the algorithm above.\n\nThe only quirk we have to watch out for is the restrictions in general don\'t include `i=1` or `i=n`. But those are valid intervals and we need to include the `1..firstRestriction` and `lastRestriction..n` intervals.\n\nTo do that I append effective restrictions `[1, 0]` and `[n, n-1]` to `restrictions`.\n\nWe also need to sort the restrictions so we get cumulative to left and right. This is the `N log(N)` time complexity part.\n\n# Complexity\n\nThis is the analysis for the in-place accumulation version, which is a bit faster than the non-in-place one that uses an auxiliary list of limits to the right.\n\n- Time complexity: `O(N log(N))`, we have to sort the limits. The rest are some `O(N)` passes\n\n- Space complexity: `O(N)`\n - Python\'s sort is Timsort, based on mergesort, and uses `O(N)` memory\n - **if you EVER use Python\'s built-in sorting, your algorithm is `O(N)` space**\n - so most of the complexity analyses for python solutions are wrong. NONE of them offer `O(1)` space because they all sort. Most of them are not `O(log(N))` space either because they use Timsort, not quicksort \n\nThe algorithm takes `O(N)` space and does three subsequent passes after sorting.\n\n## Optimizing to SC `O(log(N))` and Two Subsequent Passes\n\n### Improving Space Complexity\n\nFirst we need to reduce memory use: by writing/importing a quicksort algorithm and using that.\n\n### Reducing Passes\n\nWe can shave off a pass by merging the last two passes:\n* from right to left, we update `i, h` to account for a possibly more restrictive limit from a later `i\', h\'`\n* once we\'ve done that we now have the interval `i, h` and `i\', h\'` we need for the third pass\n* so we can do the work for this `[i, i\']` interval immediately instead of doing a third pass\n\nIs 2 pass versus three pass worth it?\n\nAlmost never. LC people are OBSESSED with this stuff, but in practice it doesn\'t matter when you data is all in memory. Real programs are limited by more substantial things like coordination among machines and checkpointing and API calls than a one-pass reduction over data in memory.\n\n**The exception to number of passes being important: big data.** Loosely speaking "big data" means "problem sizes that don\'t fit in memory on one machine." In practice that means your data is stored on disk or a network location, both of which are slow to access. Many orders of magnitude slower than main memory.\n\nIn this case it\'s **critical** for performance that you limit the number of reads from disk. Most of the time is usually spent just reading. I can confirm this professionally: when processing 70 TB data sets of finanical data, I can confirm that 90+% of the time was just spend reading data from disk and writing it back to disk.\n\nI mention this because one of the most common followups is "what if your data doesn\'t fit in memory?" If you answer with "ah well it doesn\'t really matter because BiggestChungus said so" then you fail the interview.\n\nSo be careful!\n\n# Code\n```\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n # line 1 to n\n # h >= 0\n # first h == 0\n # max diff of buildings 1\n # restrictions[i] is the height limit for i\n\n # return max possible height\n \n # max height of a building depends on the max height of building(s) to the left and right, plus one\n # limits obviously restrict height too\n\n # restrictions is [id, max_h] pairs, up to 1e5 of them\n # there are n=1e9 buildings labeled 1..n\n\n # how can we build up the skyline?\n \n # 2..n ideally have height 2\n # 3..n height 3\n # etc.\n #\n # but a restriction means a house is "locked in"\n # then if k1 .. k2 has height limits on k1 and k2\n # then k1+1 .. k2-1 have a max height\n # etc. until we find another max height that limits progress\n\n # another idea: stack question\n # we can iterate among the building restrictions in order by id\n # from the left we know the limit, but we don\'t yet know the right limit, hence the stack\n # stack is something like [l, lh, r, rh]\n # deltas in that interval are r-l\n # range(lh, rh) of those need to bring smaller up to larger\n # what goes up must come down\n # so max height is r-l-(max(lh, rh)-min(lh, rh))//2\n \n restrictions.sort()\n\n # each limit we see is\n # a left limit: prevents later buildings from getting really tall\n # and also a right limit, prevents earlier buildings from getting really tall\n \n # for a building at index i:\n # limited by building at l with max height lh according to lh+(i-l) == lh-l+i\n # r rh rh+(r-i) == rh+r-i\n # so we want the lowest lh-l on the left and rh+r on the right\n # max on left: cumulative as we process left to right\n # max on right: O(N) time and space to preprocess a list of limits\n # decreasing stack formed by processing right to left\n #\n # rlims = [(n, n-1+n)] # idx, max height limit, descending by idx\n # for r, rh in reversed(restrictions):\n # lim = r+rh\n # if lim < rlims[-1][0] + rlims[-1][1]: rlims.append((r, rh))\n\n # # makes sure we include the final range ...n with height "limit" n-1 in our answer\n # # (n-1 is the max possible height with no restrictions, more of a guard element\n # # than an actual limit)\n # def allRestrictions() -> Iterator[tuple[int, int]]:\n # for rest in restrictions: yield rest\n # yield [n, n-1]\n\n # l = 1\n # lh = 0\n # ans = 0\n # for i, h in allRestrictions():\n # # left limit on height comes from l, lh\n # # right limit on height comes from top of rlims stack, the cumulative most restrictive limit on the right\n\n # r, rh = rlims[-1]\n\n # lo = min(lh, rh)\n # hi = max(lh, rh)\n # if lo+r-l <= hi:\n # # print(f"Max height on {l=} .. {i=} is {lo+r-l}")\n # # max height limited by lower one\n # ans = max(ans, lo+r-l)\n # else:\n # # spend hi-lo of the r-l increments to bring lo up to hi\n # # then spend another pair of remaining increments to gain height in a pyramid-like pattern\n # # print(f"Max height on {l=} .. {i=} is {hi + (r-l-(hi-lo))//2}")\n # ans = max(ans, hi + (r-l-(hi-lo))//2)\n\n # if h-i < lh-l:\n # l, lh = i, h # new limit on the left\n\n # if rlims[-1][0] == i: \n # # we\'re at a right limit, later indices don\'t have this on the right\n # # so we pop it (if it\'s restrictive on the left then we\'ll have included\n # # it in the prior if statement)\n # rlims.pop()\n\n # return ans\n\n\n # better: from looking at other solutions we can modify the restrictions in place\n # first pass left to right: if current element is limited by a prior one, limit the current one\n # next pass right to left: same idea, if limited by later element then limit the current one\n \n if not restrictions: return n-1\n\n restrictions.append([1, 0])\n restrictions.append([n, n-1])\n restrictions.sort()\n\n N = len(restrictions)\n \n # forward pass: if there\'s a left limit that reduces the max height of i, change\n # i\'s restriction to the lower limit imposed from the left\n for i in range(1, N):\n prev_idx, prev_h = restrictions[i-1]\n curr_idx = restrictions[i][0]\n \n # with curr_idx-prev_idx increments the max height is prev_h + differenceInIndices\n restrictions[i][1] = min(restrictions[i][1], prev_h + curr_idx - prev_idx)\n\n # reverse pass: same idea, but account for right limits\n for i in range(N-2, -1, -1):\n next_idx, next_h = restrictions[i+1]\n curr_idx = restrictions[i][0]\n\n restrictions[i][1] = min(restrictions[i][1], next_h + next_idx - curr_idx)\n\n # third pass: for each interval find the max height, record cumulative max height\n ans = 0\n for i in range(N-1):\n l, lh = restrictions[i]\n r, rh = restrictions[i+1]\n\n # spend range increments to make lh == rh, then pairs to make a pyramid pattern to get max height\n lo = min(lh, rh)\n hi = lh+rh-lo\n ans = max(ans, hi + (r-l-(hi-lo))//2)\n\n return ans\n``` | 0 | 0 | ['Python3'] | 0 |
maximum-building-height | Sorting || C++ | sorting-c-by-scraper_nerd-g9yn | \n\n# Code\n\nclass Solution {\npublic:\n int nerd(vector<int>&v1,vector<int>&v2){\n int x1=v1[0];\n int y1=v1[1];\n int x2=v2[0];\n | Scraper_Nerd | NORMAL | 2024-06-13T17:42:25.191310+00:00 | 2024-06-13T17:42:25.191339+00:00 | 22 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int nerd(vector<int>&v1,vector<int>&v2){\n int x1=v1[0];\n int y1=v1[1];\n int x2=v2[0];\n int y2=v2[1];\n int x=(x1-y1+x2+y2)/2.0;\n int y=x-x1+y1;\n return y;\n }\n int maxBuilding(int n, vector<vector<int>>& v) {\n v.push_back({1,0});\n sort(v.begin(),v.end());\n for(int i=1;i<v.size();i++){\n v[i][1]=min(v[i][1],v[i-1][1]+v[i][0]-v[i-1][0]);\n }\n for(int i=v.size()-2;i>=0;i--){\n v[i][1]=min(v[i][1],v[i+1][1]+v[i+1][0]-v[i][0]);\n }\n int res=0;\n for(int i=1;i<v.size();i++){\n res=max(nerd(v[i-1],v[i]),res);\n }\n if(v[v.size()-1][0]!=n){\n res=max(res,v[v.size()-1][1]+n-v[v.size()-1][0]);\n }\n return res;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-building-height | Three passes O(len(restrictions)), beating 98.53% in python | three-passes-olenrestrictions-beating-98-fl5u | This is really not an easy \'hard\'.\n\nFirst, note n could be as much as 10e9, which is too much for a typical O(n) leetcode question. So definitely we should | MaxOrgus | NORMAL | 2023-12-27T02:56:43.511846+00:00 | 2023-12-27T02:56:43.511867+00:00 | 18 | false | This is really not an easy \'hard\'.\n\nFirst, note n could be as much as 10e9, which is too much for a typical O(n) leetcode question. So definitely we should not consider looping through n, which was I attempted at first, and resulted in TLE.\n\nIn stead, we focus only on the points where restrictions are casted, whose amount N allow for O(N) solutions. Maximum points we look for might be in between these points of course, but in the gaps things go linearly, and can be handled later.\n\nAppend two \'natural restrictions\' to both ends of the restriction array -- that is, at place 1(note 1-index) maxmimum height being 0 and at place N being N-1.\n\nLoop the restrictions from left to right. At each point, the maximum height increase from last point would be their distance in the x axis, and we go dp with the transition equation lastmax[i] = min(lastmax[i-1] + d, limit[i]). \n\nNote the \'increase limit\' work form both side of a point, so we are doing the same thing from right to left again.\n\nThus we gain an array where the actual restriction at each point listed in the original resctriction points are stored.The initial guess of the maximum height would be the maximum in it.\n\nBut we know the answer could also be somewhere in between. Between every two consecutive points in that array, we may go as much as a steps and b steps down, satisfying:\n\na + b = x[i+1] - x[i]\na - b = limit[i+1] - limit[i]\n\nsolve for a, and add it to limit x, we acquire the maximum height. \n\nSome subtletis come into play in the last step. The count of steps up a could be *.5, in which case we simply omit the half points since we can also choose to go neither up nor down, unless there is no points between two limits, where we simply skip.\n\nReturn the maximum of maximum a and maximum actual height limit and we make it.\n\n# Code\n```\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n \n restrictions.sort() \n restrictions = [[1,0]] + restrictions + [[n,n-1]]\n N = len(restrictions)\n lastmax = [0 for i in range(N)]\n \n for i in range(1,N):\n d = restrictions[i][0] - restrictions[i-1][0]\n lastmax[i] = min(lastmax[i-1]+d,restrictions[i][1])\n\n for i in range(N-2,-1,-1):\n d = restrictions[i+1][0] - restrictions[i][0]\n lastmax[i] = min(lastmax[i+1]+d,lastmax[i])\n res = max(lastmax)\n for i in range(N-1):\n dist = restrictions[i+1][0] - restrictions[i][0]\n if dist < 2: continue\n heightdiff = lastmax[i+1] - lastmax[i]\n a = (dist + heightdiff) // 2\n res = max(res,lastmax[i]+a)\n return res \n\n\n\n \n``` | 0 | 0 | ['Dynamic Programming', 'Python3'] | 1 |
maximum-building-height | [RUNTIME 100%] | runtime-100-by-gztyss-mib1 | Intuition\n Describe your first thoughts on how to solve this problem. \n- Each restriction point can create line by:\ny = x + (x_1-y_1) #for slope 1 and point | GzTyss | NORMAL | 2023-12-26T17:02:51.857127+00:00 | 2023-12-26T17:02:51.857163+00:00 | 153 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Each restriction point can create line by:\n$$y = x + (x_1-y_1) $$ #for slope 1 and point [x1,y1]\n$$y = -x + (x_2+y_2) $$ #for slope -1 and point [x2,y2]\n- for Increment line, if (x1-y1)==(x2-y2) -> both point is same line \n- for Decrement line, if (x1+y1)==(x2+y2) -> both point is same line\n- if x2>x1 and diff2 < diff1 -> point1 can\'t reach point2 \nso we have to filter non-decreasing diff so every point will get reached (forward)\n- if x2<x1 and sum2 < sum1 -> point1 can\'t reach point2 \nso we have to filter non-increasing sum (backward) so every point will get reached from both sides\n- finally, we will get maxHeight when increment from [x1,y1] to highest point [x_h,y_h] then decrement to [x2,y2]:\n$$ maxHeight = x_h + (x_1-y_1) $$ #increment function from point1\n$$ maxHeight = -x_h + (x_2+y_2) $$ #decrement function from point2\n$$ maxHeight = [(x_1-y_1) + (x_2+y_2)]/2 $$ #plus two equation will get function to find local maximum height between two restriction point\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. add [1,0] first\n2. filter only possible reached restriction point from **previous** restriction point by increment one\n3. filter only possible restriction point reaching to **next** restriction point by decrement one\n4. add maximum height for last buildings from **last restriction point**\n5. calculate available height **between** two valid restriction point\n6. return **maximum height** from available height\n\n# Complexity\n- Time complexity: $$O(NlogN)$$ \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```\n#Readability version\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n # Set the initial height for the 1st building\n restrictions.append([1, 0])\n restrictions.sort()\n\n # Process restrictions to find the valid ones for reaching previous restrictions\n valid_restrictions_forward = []\n temp_diff = 0\n for id, ht in restrictions:\n current_diff = id - ht\n if current_diff >= temp_diff:\n temp_diff = current_diff\n valid_restrictions_forward.append([id, ht])\n\n # Process valid restrictions backward to find the ones for reaching next restrictions\n valid_restrictions_backward = []\n temp_sum = n + n - 1\n for id, ht in valid_restrictions_forward[::-1]:\n current_sum = id + ht\n if current_sum <= temp_sum:\n temp_sum = current_sum\n valid_restrictions_backward.append([id, ht])\n\n # Reverse the backward valid restrictions to get the correct order\n valid_restrictions_backward.reverse()\n\n # Add maximum height for the last building due to the last restriction\n if valid_restrictions_backward[-1][0] != n:\n valid_restrictions_backward.append([n, valid_restrictions_backward[-1][1] + n - valid_restrictions_backward[-1][0]])\n\n # Calculate the maximum height\n max_height = 0\n for i in range(len(valid_restrictions_backward) - 1):\n x1, y1 = valid_restrictions_backward[i]\n x2, y2 = valid_restrictions_backward[i + 1]\n available_height = (-x1 + y1 + x2 + y2) // 2\n if available_height > max_height:\n max_height = available_height\n\n return max_height\n\n``` | 0 | 0 | ['Python3'] | 1 |
maximum-building-height | Unique approach,Explanation added | unique-approachexplanation-added-by-rish-xvzg | \n//dry run for better understanding \nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& arr) {\n arr.push_back({1,0}); //always | rishabhprasanna | NORMAL | 2023-08-02T13:21:42.179183+00:00 | 2023-08-02T13:21:42.179223+00:00 | 28 | false | ```\n//dry run for better understanding \nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& arr) {\n arr.push_back({1,0}); //always a constraint \n sort(arr.begin(),arr.end());\n //sorting ids of buildings \n int m=arr.size();\n vector<int>mark(m,arr[m-1][1]);\n //max height each building can have\n for(int i=m-2;i>=0;i--){ //max height i can have considering constraint on i+1 \n int dist=arr[i+1][0]-arr[i][0];\n int maxno=mark[i+1]+dist; \n maxno=min(maxno,arr[i][1]);\n mark[i]=maxno;\n }\n for(int i=1;i<m;i++){ //max height i can have considering constraint on i-1 \n int diff=arr[i][0]-arr[i-1][0];\n mark[i]=min(mark[i],mark[i-1]+diff);\n }\n //now mark will have the max values each of the m id indexes can have its always optimal to give these m buildings the max height \n //now we only have to find out the max heights of buildings in each range \n //suppose there are 2 restrictions [(2,1),(6,1)] then 0 1 2 3 2 1 can be the heights so in this case the max height building is not any corner point and lies in b/w the range say i and i+1 so we have to consider this case also \n int last=n-arr[m-1][0];\n int ans=last+mark[m-1]; //corner case that after last restriction till n we will increase our height by 1 \n //for calculating the max building in the interval i to i+1 we can use some formula but why to think of it when we can apply binary search \n //we know that i and i+1 heights are fixed so we also know that the figure from i to i+1 will be a mountain(means increase to a point and then decrease to i+1) so we can apply binary search on the peak element self explanatory code \n for(int i=1;i<m;i++){ //checking b/w interval i and i-1 \n int dist=arr[i][0]-arr[i-1][0];\n int start=mark[i-1];\n int end=mark[i];\n ans=max(ans,mark[i]);\n int s=max(mark[i-1],mark[i]);\n int e=1e9;\n int res=s;\n while(s<=e){\n int m=(s+e)>>1;\n int tot=m-mark[i-1];\n tot+=(m-mark[i]);\n if(tot<=dist){\n res=m;\n s=m+1;\n }\n else{\n e=m-1;\n }\n }\n ans=max(ans,res);\n }\n return ans;\n }\n};\n```\n //worst case time is max(mlogn,mlogm)\n //additonal ..try to think of how can we solve this if adjacent heights cannot be same | 0 | 0 | ['Sorting', 'Binary Tree'] | 0 |
maximum-building-height | Simple and fast C++ SOLUTION | simple-and-fast-c-solution-by-kevinjoyth-c54x | 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 | kevinjoythomas7 | NORMAL | 2023-06-14T17:41:46.119703+00:00 | 2023-06-14T17:41:46.119720+00:00 | 124 | 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\n \n int maxBuilding(int n, vector<vector<int>>& rest) {\n //priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>pq;\n \n int maxH = 0;\n int current = 0;\n rest.insert(rest.end(),{{1,0},{n,n-1}});\n sort(begin(rest),end(rest));\n for(int i=0;i<rest.size()-1;i++){\n int h1 = rest[i][1];\n int h2 = rest[i+1][1];\n int current = h1 + abs(rest[i][0]-rest[i+1][0]);\n if(current>h2){\n current = h2 + (current-h2)/2;\n }\n maxH = max(maxH,current);\n rest[i+1][1] = min (current, h2);\n }\n reverse(begin(rest),end(rest));\n maxH = 0;\n current = 0;\n for(int i=0;i<rest.size()-1;i++){\n int h1 = rest[i][1];\n int h2 = rest[i+1][1];\n int current = h1 + abs(rest[i][0]-rest[i+1][0]);\n if(current>h2){\n current = h2 + (current-h2)/2;\n }\n maxH = max(maxH,current);\n rest[i+1][1] = min (current, h2);\n }\n\n return maxH;\n \n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-building-height | Python || sort, greedy || O(m log m) | python-sort-greedy-om-log-m-by-hanna9221-ea3l | Add [1,0] to restrictions, then sort restrictions by index in ascending order.\n2. We will do the same procedure twice, forward and backward. The procedure is a | hanna9221 | NORMAL | 2023-04-15T12:16:14.955239+00:00 | 2023-04-15T12:44:15.382628+00:00 | 139 | false | 1. Add `[1,0]` to `restrictions`, then sort `restrictions` by index in ascending order.\n2. We will do the same procedure twice, forward and backward. The procedure is as following:\n2-1. Move to `(idx_2, res_2)` and check previous `(idx_1, res_1)`. \n2-2. Let `steps = abs(idx_1-idx_2)`. Starting from `idx_1`, the maximal height we can reach at \'idx_2\' would be `res_1 + steps`.\n2-3. So if `res_2 > res_1 + steps`, replace `res_2` by `res_1 + steps`.\n3. After that, we\'re ready to find the answer. \nGiven two adjacent restrictions, `(idx_1, res_1)` and `(idx_2, res_2)`, suppose the maximal height between them(inclusive) is `h`.\n`(h-res_1) + (h-res_2) = steps`, which implies `h = (steps+res_1+res_2) // 2`.\nAnd don\'t forget the last segment between `restrictions[-1][0]` and `n`.\n```\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n restrictions = [[1, 0]] + restrictions\n restrictions.sort()\n m = len(restrictions)\n \n # from 1 to n\n for i, (idx_2, res_2) in enumerate(restrictions[1:], start=1):\n idx_1, res_1 = restrictions[i-1]\n steps = idx_2 - idx_1\n if res_2 - res_1 > steps:\n restrictions[i][1] = res_1 + steps\n \n # from n to 1\n for i, (idx_2, res_2) in enumerate(restrictions[m-2:0:-1]):\n idx_1, res_1 = restrictions[m-i-1]\n steps = idx_1 - idx_2\n if res_2 - res_1 > steps:\n restrictions[m-2-i][1] = res_1 + steps\n \n # find maximal height\n idx, res = restrictions[-1]\n ans = res + (n-idx)\n for i, (idx_2, res_2) in enumerate(restrictions[1:], start=1):\n idx_1, res_1 = restrictions[i-1]\n steps = idx_2 - idx_1\n ans = max(ans, (steps + res_1 + res_2) // 2)\n return ans | 0 | 0 | ['Python3'] | 0 |
maximum-building-height | BS ON ANSWER | bs-on-answer-by-shivral-hwiq | \n\n# Code\n\nclass Solution:\n def maxBuilding(self, n: int, rt: List[List[int]]) -> int:\n rt.append([0,-1])\n rt.append([n,float("inf")])\n | shivral | NORMAL | 2023-03-23T09:04:01.157294+00:00 | 2023-03-23T09:04:01.157322+00:00 | 91 | false | \n\n# Code\n```\nclass Solution:\n def maxBuilding(self, n: int, rt: List[List[int]]) -> int:\n rt.append([0,-1])\n rt.append([n,float("inf")])\n rt.sort()\n n=len(rt)\n for i in range(1,n):\n rt[i][1]=min(rt[i][0]-rt[i-1][0]+rt[i-1][1],rt[i][1])\n for i in range(n-2,-1,-1):\n if rt[i+1][-1]<rt[i][-1]:\n req=rt[i][-1]-rt[i+1][-1]\n has=rt[i+1][0]-rt[i][0]\n if has<req:\n rt[i][1]-=(req-has)\n lo=0\n hi=10**9+1\n ans=-1\n while lo<=hi:\n mid=(lo+hi)//2\n f=False\n for i in range(1,len(rt)):\n inc=max(mid-rt[i-1][1],0)\n dec=max(mid-rt[i][1],0)\n\n if inc +dec<=rt[i][0]-rt[i-1][0]:\n f=True\n break\n if f:\n ans=mid\n lo=mid+1\n else:\n hi=mid-1\n return ans\n\n``` | 0 | 0 | ['Python3'] | 0 |
maximum-building-height | Python (Simple Maths) | python-simple-maths-by-rnotappl-1dv8 | 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 | 2023-03-14T16:27:02.072483+00:00 | 2023-03-14T16:27:02.072509+00:00 | 85 | 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 maxBuilding(self, n, restrictions):\n restrictions.extend([[1,0],[n,n-1]])\n restrictions.sort()\n m = len(restrictions)\n\n for i in range(1,m):\n restrictions[i][1] = min(restrictions[i][1],restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0])\n\n for i in range(m-2,-1,-1):\n restrictions[i][1] = min(restrictions[i][1],restrictions[i+1][1] + restrictions[i+1][0] - restrictions[i][0])\n\n max_val = 0\n\n for i in range(1,m):\n l,h1 = restrictions[i-1]\n r,h2 = restrictions[i]\n max_val = max(max_val,max(h1,h2) + (r-l-abs(h1-h2))//2)\n\n return max_val\n\n``` | 0 | 0 | ['Python3'] | 0 |
maximum-building-height | Just a runnable solution | just-a-runnable-solution-by-ssrlive-5h0p | Code\n\nimpl Solution {\n pub fn max_building(n: i32, restrictions: Vec<Vec<i32>>) -> i32 {\n fn pass(r: &mut Vec<Vec<i32>>) -> i32 {\n let | ssrlive | NORMAL | 2023-02-23T11:01:45.574942+00:00 | 2023-02-23T11:01:45.574974+00:00 | 26 | false | # Code\n```\nimpl Solution {\n pub fn max_building(n: i32, restrictions: Vec<Vec<i32>>) -> i32 {\n fn pass(r: &mut Vec<Vec<i32>>) -> i32 {\n let mut res = 0;\n for i in 0..r.len() - 1 {\n let h1 = r[i][1];\n let h2 = r[i + 1][1];\n let mut h = h1 + (r[i + 1][0] - r[i][0]).abs();\n if h > h2 {\n h = h2 + (h - h2) / 2;\n }\n res = res.max(h);\n r[i + 1][1] = h.min(h2);\n }\n res\n }\n\n let mut r = restrictions;\n r.push(vec![1, 0]);\n r.push(vec![n, n - 1]);\n r.sort();\n pass(&mut r);\n r.reverse();\n pass(&mut r)\n }\n}\n``` | 0 | 0 | ['Rust'] | 0 |
maximum-building-height | C# Solution | c-solution-by-m67186636-a6by | 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 | m67186636 | NORMAL | 2023-02-04T14:08:04.188654+00:00 | 2023-02-04T14:08:04.188687+00:00 | 39 | 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```\npublic class Solution {\n public int MaxBuilding(int n, int[][] restrictions) {\n \n if (restrictions.Length == 0) \n return n - 1;\n Array.Sort(restrictions, (a, b) => a[0] - b[0]);\n for (int i = restrictions.Length-1; i >0; i--)\n restrictions[i - 1][1] = Math.Min(restrictions[i - 1][1], restrictions[i][1] + restrictions[i][0] - restrictions[i - 1][0]);\n var result = 0;\n void Calc(int[] start,int[] end)\n {\n if (end[1] > start[1] + end[0] - start[0])\n result=Math.Max(result,end[1] = start[1] + end[0] - start[0]);\n else\n result = Math.Max(result,(start[1] + end[0] - start[0] + end[1]) / 2);\n }\n var current = new int[] { 1,0};\n foreach ( var restriction in restrictions)\n Calc(current, current = restriction);\n Calc(current, new[] { n, n - 1 });\n return result;\n }\n}\n``` | 0 | 0 | ['C#'] | 0 |
maximum-building-height | 91.43% Faster || Adjust Previous Tower height based on the ones next to it | 9143-faster-adjust-previous-tower-height-a9dh | 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 | recker2903 | NORMAL | 2023-01-29T19:27:58.653861+00:00 | 2023-01-29T19:28:33.538149+00:00 | 152 | 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\n int maxBuilding(int n, vector<vector<int>>& restrictions) {\n ll m=restrictions.size(),answer=INT_MIN,current=0,prev_index=1;\n if(restrictions.size()==0){\n return n-1;\n }\n sort(restrictions.begin(),restrictions.end()); \n for(ll i=m-1;i>0;i--){\n if(restrictions[i][1]<restrictions[i-1][1]){\n if(restrictions[i-1][1]-restrictions[i][1]>restrictions[i][0]-restrictions[i-1][0]){\n restrictions[i-1][1]=restrictions[i][1]+restrictions[i][0]-restrictions[i-1][0];\n }\n }\n }\n for(ll i=0;i<m;i++){\n ll height_diff=restrictions[i][1]-current,distance=restrictions[i][0]-prev_index;\n if(height_diff>0){\n if(distance>height_diff){\n answer=max(answer,restrictions[i][1]+((distance-height_diff)/2));\n current=restrictions[i][1];\n }\n else{\n current+=(distance);\n answer=max(answer,current);\n }\n }\n else if(height_diff<0){\n if(distance>height_diff){\n answer=max(answer,current+((distance-abs(height_diff))/2));\n }\n else{\n answer=max(answer,(ll)restrictions[i][1]);\n }\n current=restrictions[i][1];\n }\n else{\n answer=max(answer,current+(distance/2));\n }\n prev_index=restrictions[i][0];\n }\n \n return max(answer,current+n-prev_index);\n }\n};\n``` | 0 | 0 | ['Sorting', 'C++'] | 0 |
maximum-building-height | Python 6-lines | python-6-lines-by-mfatihuslu-v92x | Intuition\n Describe your first thoughts on how to solve this problem. \n\nFirst, sort restrictions with respect to first limiting the height of buildings when | mfatihuslu | NORMAL | 2022-12-21T19:04:15.787794+00:00 | 2022-12-21T19:05:42.889168+00:00 | 121 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nFirst, sort restrictions with respect to first limiting the height of buildings when we traverse line from left to right.\n\nThen, traverse through array and store rightmost restriction in every point. In every comparison, leftmost and rightmost restriction line\'s intersection point will be the maximum allowed height at that point. \n\nOne thing should be considered is intersection points have to be in the [0,n] range.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe update ans when we encounter a point which allows longer building. \n\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxBuilding(self, n: int, re: List[List[int]]) -> int:\n re.sort(key=lambda i:i[0]+i[1])\n ans, b = 0, [1,0]\n for r in re:\n ans = max(ans,(min(2*n-b[0]+b[1],r[0]+r[1])-(b[0]-b[1]))//2)\n if b[0]-b[1] < r[0]-r[1]: b = [r[0],r[1]]\n return max(ans,n-b[0]+b[1])\n``` | 0 | 0 | ['Python3'] | 0 |
maximum-building-height | Presumably fast solution, nothing to compare to | presumably-fast-solution-nothing-to-comp-3kuu | Intuition\n Describe your first thoughts on how to solve this problem. \nIt is enough to look for maximum heights at each restricted buinding and at the maximum | mbeceanu | NORMAL | 2022-11-21T23:22:10.771416+00:00 | 2022-11-21T23:22:10.771453+00:00 | 87 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt is enough to look for maximum heights at each restricted buinding and at the maximum points between each pair of consecutive restricted buildings.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nI did it in three passes: first from left to right to establish maximum bounds coming from the left, then from right to left to establish maximum bounds coming from the right, and once more to establish maximum heights between restricted buildings.\n\n# Complexity\n- Time complexity: Linear.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: Linear.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def maxBuilding(self, n, restrictions):\n """\n :type n: int\n :type restrictions: List[List[int]]\n :rtype: int\n """\n h=[(1,0)]\n restrictions.sort(key=lambda x:x[0])\n for rest in restrictions:\n tmp=min(rest[1], h[-1][1]+rest[0]-h[-1][0])\n h.append((rest[0], tmp))\n if len(restrictions)==0 or restrictions[-1]!=n:\n h.append((n, h[-1][1]+n-h[-1][0]))\n l=len(h)\n for i in range(l-2, -1, -1):\n tmp=min(h[i][1], h[i+1][1]+h[i+1][0]-h[i][0])\n h[i]=(h[i][0], tmp)\n ans=0\n for i in range(l-1):\n tmp=(h[i+1][1]+h[i][1]+h[i+1][0]-h[i][0])>>1\n if tmp>ans:\n ans=tmp\n return ans\n\n\n \n``` | 0 | 0 | ['Python'] | 0 |
maximum-building-height | TC: O(N) SC: O(1) Greedy Approach Explained Python | tc-on-sc-o1-greedy-approach-explained-py-5187 | For each building you want to find the most constraining height either on left or right\nm = len(restrictions) <= 10^5 so O(m^2) is too slow\nBut we can find bi | sarthakBhandari | NORMAL | 2022-10-08T14:36:38.031388+00:00 | 2022-10-08T14:40:27.218995+00:00 | 83 | false | For each building you want to find the most constraining height either on left or right\nm = len(restrictions) <= 10^5 so O(m^2) is too slow\nBut we can find biggest restriction on left for each element is one loop, and\nfind the biggest restriction on right for each element in one loop aswell\n\nlet curr biggest restriction on left be (c_b,c_h) where c_b is building location and c_h is the height of that building\nif restriction[i][1] < i - c_b + c_h then (i, restriction[i][1]) is the new biggest restriction on left\nif restriction[i][1] > i - c_b + c_h then apply the restriction to building i\n\nBut you dont want to calulcate restriction for every building because n <= 10^9\nSo you just work with the intervals in restrictions\nand max height in that interval is the intersection of two lines:\ny1 = (x - left_building_location) + height_left_building\ny2 = (right_building_location - x) + height_right_building\n\n```\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n restrictions += [[1, 0]]\n restrictions.sort() #sort by building number\n\n #if last building is not in restriction add it\n #and its height must be <= n-1 because first building is 0\n if restrictions[-1][0] != n: restrictions.append([n, n-1])\n \n c = 1; c_h = 0\n for i in range(len(restrictions)):\n b,h = restrictions[i]\n\n if (b-c) + c_h < h:\n restrictions[i][1] = (b-c) + c_h\n else:\n c = b; c_h = h \n \n c, c_h = restrictions[-1]\n for i in range(len(restrictions)-1, -1, -1):\n b,h = restrictions[i]\n\n if (c-b) + c_h < h:\n restrictions[i][1] = (c-b) + c_h\n else:\n c = b; c_h = h \n \n ans = 0\n for i in range(len(restrictions) - 1):\n left, left_h = restrictions[i]\n right, right_h = restrictions[i+1]\n\n #y1 = (x - left) + left_h\n #y2 = (rigth - x) + right_h, their intersection is the max_h in that interval\n # x - left + l_h = right - x + r_h\n # x = (right + left + r_h - l_h)/2\n # y = (right + left + r_h - l_h)/2 - left + l_h\n location = (right + left + right_h - left_h)//2 #building_id must be integer\n height = location - left + left_h\n ans = max(ans, height)\n\n return ans\n``` | 0 | 0 | ['Python3'] | 0 |
maximum-building-height | simple c++ sol | simple-c-sol-by-adtyaofficial17-f79d | ```\nclass Solution {\npublic:\n int maxBuilding(int n, vector>& res) {\n \n if(res.size()==0)\n return n-1;\n \n vect | AdityaGupta-Official | NORMAL | 2022-08-26T18:51:17.295523+00:00 | 2022-08-26T18:51:17.295563+00:00 | 66 | false | ```\nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& res) {\n \n if(res.size()==0)\n return n-1;\n \n vector<int> mad={1,0};\n sort(res.begin(),res.end());\n res.insert(res.begin(),mad);\n /* for(auto it:res)\n {\n cout<<it[0]<<" "<<it[1]<<endl;\n }*/\n \n for(int i=1;i<res.size();i++)\n {\n int val=res[i][0]-res[i-1][0];\n if(val+res[i-1][1]<=res[i][1])\n {\n res[i][1]=res[i-1][1]+val;\n \n }\n }\n for(int i=(res.size()-1);i>0;i--)\n {\n int val=res[i][0]-res[i-1][0];\n if((res[i][1]+val)<=res[i-1][1])\n {\n res[i-1][1]=res[i][1]+val;\n }\n }\n int ans=0;\n for(int i=1;i<res.size();i++)\n {\n int val=res[i][0]-res[i-1][0];\n if((val+res[i-1][1])<=res[i][1])\n {\n ans=max(ans,res[i][1]); \n }\n else{\n if(val==1)\n ans=max(ans,min(res[i][1],res[i-1][1])+(val/2));\n else{\n ans=max(ans,(res[i][1]+res[i-1][1]+val)/2);\n }\n }\n \n }\n \n int val=n-res[res.size()-1][0];\n ans=max(ans,res[res.size()-1][1]+val);\n \n \n return ans;\n }\n}; | 0 | 0 | [] | 0 |
maximum-building-height | Java | Trim Backward, then Count Forward | java-trim-backward-then-count-forward-by-qahn | First, make the restriction counts, that is, if we have a [10, 0], and [9,9] trim that [9,9] such that it becomes the actual limit, i.e. [9,1]. This will be imp | Student2091 | NORMAL | 2022-07-31T22:21:34.090141+00:00 | 2022-07-31T22:25:15.320783+00:00 | 154 | false | 1. First, make the restriction counts, that is, if we have a `[10, 0]`, and `[9,9]` trim that `[9,9]` such that it becomes the actual limit, i.e. `[9,1]`. This will be important for the math we need later. \n\n2. Then, we start from building 1, set `x = 1, y = 0`, meaning the current height is at 0 with `x` at 1. For each restriction interval, we will have to solve for `y+a` in the pic below: This is why we had to trim it in step 1. \n\nSolved for `y+a`, we get `y+a = (r[0]+r[1]-(x+y))/2+y`.\nObviously, it is not the only possibility, it is possible that the restriction for the next building is so high that it won\'t be able to reach that, so in that case, the equation above won\'t hold, but we will have an very intuitive `y+a = y+r[0]-x`\nThis concludes that `y+a = min((r[0]+r[1]-(x+y))/2+y, y+r[0]-x)`\n\n3. There is an invislble restriction `[n, n-1]`. Add that.\n\n\n#### Java\n \n```Java\nclass Solution {\n public int maxBuilding(int n, int[][] R) {\n Arrays.sort(R, Comparator.comparingInt(o -> -o[0]));\n int cur = (int)2e9, pre = -1, ans = 0, x = 1, y = 0;\n for (int[] r : R){\n cur = Math.min(r[1], pre-r[0]+cur);\n r[1] = cur;\n pre = r[0];\n }\n for (int i = R.length-1; true; i--){\n // a + b = r[0] - x;\n // a - b = r[1] - y;\n // y + a = ;\n int[] r = i == -1? new int[]{n, n-1} : R[i];\n int res = Math.min((r[0]+r[1]-(x+y))/2+y, y+r[0]-x);\n ans = Math.max(ans, res);\n x = r[0];\n y = Math.min(res, r[1]);\n if (i == -1){\n return ans;\n }\n }\n }\n}\n``` | 0 | 0 | ['Math', 'Java'] | 0 |
maximum-building-height | 100% faster | O(nlogn) | Well commented | 100-faster-onlogn-well-commented-by-yezh-f30h | We process in 3 steps.\n\n1. Left->right. Update height restriction on (i + 1)-th building based on restriction on i-th build \n2. Right->left\n3. For adjacent | yezhizhen | NORMAL | 2022-04-15T07:41:48.411210+00:00 | 2022-04-15T07:49:06.037680+00:00 | 170 | false | We process in 3 steps.\n\n1. Left->right. Update height restriction on (i + 1)-th building based on restriction on i-th build \n2. Right->left\n3. For adjacent two restrictions, let h be the height restriction differences, x be the difference in x-axis. \nAssume you go up "a" steps and down by "x-a" steps,\nSolve equation \na - (x-a) = h gives a = (h+x) / 2; \nThen the tallest in between can be min(height[i], height[i+1]) + a\n\n\n```\nint maxBuilding(int n, vector<vector<int>>& res) {\n if(res.empty()) return n - 1;\n sort(res.begin(), res.end());\n //propagate build 1\n res[0][1] = min(res[0][1], res[0][0] - 1);\n //left to right\n for(int i = 0; i < res.size() - 1; i++)\n res[i + 1][1] = min(res[i+1][1], res[i][1] + res[i+1][0] - res[i][0]); \n //right to left\n for(int i = res.size() - 1; i > 0; i--)\n res[i - 1][1] = min(res[i-1][1], res[i][1] - res[i-1][0] + res[i][0]); \n //leftmost to first restr\n int max_h = (res[0][1] + res[0][0] - 1 ) / 2; \n for(int i = 0; i < res.size() - 1; i++)\n {\n int x = res[i+1][0] - res[i][0];\n int h = abs(res[i+1][1] - res[i][1]);\n int climb = (x+h)/2;\n max_h = max(max_h, climb + min(res[i][1],res[i+1][1]));\n }\n //to the rightmost of restriction\n max_h = max(max_h, res.back()[1] + n - res.back()[0]);\n return max_h;\n }\n```\nFor simplicity, one can insert(1, 0) on the left and (n, INT_MAX) on the back. But inserting in front would result in shifting of vector with extra O(n) time. So I choose not to. | 0 | 0 | ['C'] | 0 |
maximum-building-height | Python | 3 passes | O(nlogn) | python-3-passes-onlogn-by-aryonbe-xm4r | \nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n arr = restrictions\n arr.extend([[1,0],[n,n-1]])\n | aryonbe | NORMAL | 2022-03-24T01:37:19.965754+00:00 | 2022-04-22T12:58:28.006995+00:00 | 208 | false | ```\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n arr = restrictions\n arr.extend([[1,0],[n,n-1]])\n arr.sort()\n n = len(arr)\n for i in range(1,n):\n arr[i][1] = min(arr[i][1], arr[i-1][1]+arr[i][0]-arr[i-1][0])\n for i in range(n-2,-1,-1):\n arr[i][1] = min(arr[i][1], arr[i+1][1]+arr[i+1][0]-arr[i][0])\n res = 0\n for i in range(1,n):\n\t\t\t#position where height can be the highest between arr[i-1][0] and arr[i][0]\n k = (arr[i][1]-arr[i-1][1]+arr[i][0]+arr[i-1][0])//2\n res = max(res, arr[i-1][1]+k-arr[i-1][0])\n return res\n ``` | 0 | 0 | ['Python'] | 1 |
maximum-building-height | C++ O(N * LogN) time and O(1) | Fast and easy to understand (N is the length of the array) | c-on-logn-time-and-o1-fast-and-easy-to-u-jzau | \nint maxBuilding(int k, vector<vector<int>>& restrictions) {\n restrictions.push_back({1, 0});\n int n = restrictions.size();\n sort(restr | dineshbs444 | NORMAL | 2022-02-19T19:38:18.307167+00:00 | 2022-02-19T19:38:18.307194+00:00 | 238 | false | ```\nint maxBuilding(int k, vector<vector<int>>& restrictions) {\n restrictions.push_back({1, 0});\n int n = restrictions.size();\n sort(restrictions.begin(), restrictions.end());\n for(int i = 0 ; i < n - 1; i++) {\n int distance = restrictions[i + 1][0] - restrictions[i][0];\n if((restrictions[i][1] + distance) < restrictions[i + 1][1]) {\n restrictions[i + 1][1] = restrictions[i][1] + distance;\n }\n }\n for(int i = n - 1 ; i > 0; i--) {\n int distance = restrictions[i][0] - restrictions[i - 1][0];\n if((restrictions[i][1] + distance) < restrictions[i - 1][1]) {\n restrictions[i - 1][1] = restrictions[i][1] + distance;\n }\n }\n int ans = 0;\n for(int i = 0; i < n; i++) {\n if(i == n - 1) {\n int distance = k - restrictions[i][0];\n ans = max(ans, restrictions[i][1] + distance);\n continue;\n }\n int distance = restrictions[i + 1][0] - restrictions[i][0];\n int rem = (distance - 1) - abs(restrictions[i + 1][1] - restrictions[i][1]);\n ans = max(ans, max(restrictions[i][1], restrictions[i + 1][1]) + ((rem + 1) / 2));\n }\n return ans;\n }\n``` | 0 | 0 | ['C', 'C++'] | 0 |
maximum-building-height | Golang heap solution, beats 100% | golang-heap-solution-beats-100-by-tjucod-9tod | go\nfunc maxBuilding(n int, restrictions [][]int) int {\n\t// no restrictions, increase one by one\n\tif len(restrictions) == 0 {\n\t\treturn n-1\n\t}\n\t// sor | tjucoder | NORMAL | 2022-01-06T09:15:03.391284+00:00 | 2022-01-06T09:15:03.391329+00:00 | 100 | false | ```go\nfunc maxBuilding(n int, restrictions [][]int) int {\n\t// no restrictions, increase one by one\n\tif len(restrictions) == 0 {\n\t\treturn n-1\n\t}\n\t// sort by index\n\tsort.Slice(restrictions, func(i, j int) bool {\n\t\treturn restrictions[i][0] < restrictions[j][0]\n\t})\n\t// make height valid\n\tfor _, restrict := range restrictions {\n\t\tif restrict[1] >= restrict[0] {\n\t\t\trestrict[1] = restrict[0]-1\n\t\t}\n\t}\n\t// Heap item: [indexOfRestrictions, indexOfBuildings, restrictHeight]\n\th := &Heap{}\n\tfor i, v := range restrictions {\n\t\theap.Push(h, []int{i, v[0], v[1]})\n\t}\n\tprocessed := make([]bool, len(restrictions))\n\tfor h.Len() != 0 {\n\t\telem := heap.Pop(h).([]int)\n\t\tif processed[elem[0]] == true {\n\t\t\tcontinue\n\t\t}\n\t\tprocessed[elem[0]] = true\n\t\t// refresh restrictions\n\t\trestrictions[elem[0]][1] = elem[2]\n\t\tif elem[0] > 0 && processed[elem[0]-1] == false {\n\t\t\tleftElem := restrictions[elem[0]-1]\n\t\t\tmaxLeftElemHeight := elem[2] + elem[1] - leftElem[0]\n\t\t\tif leftElem[1] > maxLeftElemHeight {\n\t\t\t\tleftElem[1] = maxLeftElemHeight\n\t\t\t}\n\t\t\theap.Push(h, []int{elem[0]-1, leftElem[0], leftElem[1]})\n\t\t}\n\t\tif elem[0] < len(restrictions)-1 && processed[elem[0]+1] == false {\n\t\t\trightElem := restrictions[elem[0]+1]\n\t\t\tmaxRightElemHeight := elem[2] + rightElem[0] - elem[1]\n\t\t\tif rightElem[1] > maxRightElemHeight {\n\t\t\t\trightElem[1] = maxRightElemHeight\n\t\t\t}\n\t\t\theap.Push(h, []int{elem[0]+1, rightElem[0], rightElem[1]})\n\t\t}\n\t}\n\t// add restrict for last building if not exist\n\tif restrictions[len(restrictions)-1][0] != n {\n\t\trestrictions = append(restrictions, []int{n, restrictions[len(restrictions)-1][1] + n - restrictions[len(restrictions)-1][0]})\n\t}\n\t// calculate max building height\n\tmaxHeight := 0\n\tprevIndex, preHeight := 1, 0\n\tfor _, restrict := range restrictions {\n\t\tif restrict[1] != preHeight + restrict[0] - prevIndex && restrict[1] != preHeight - restrict[0] + prevIndex {\n\n\t\t}\n\t\tif curHeight := getMaxHeight(preHeight, restrict[1], restrict[0]-prevIndex); curHeight > maxHeight {\n\t\t\tmaxHeight = curHeight\n\t\t}\n\t\tprevIndex, preHeight = restrict[0], restrict[1]\n\t}\n\treturn maxHeight\n}\n\nfunc getMaxHeight(left, right, gap int) int {\n\tif left < right {\n\t\tgap -= right - left\n\t\tleft = right\n\t} else if left > right {\n\t\tgap -= left - right\n\t\tright = left\n\t}\n\treturn left + gap / 2\n}\n\ntype Heap [][]int\n\nfunc (p Heap) Len() int { return len(p) }\nfunc (p Heap) Less(i, j int) bool { return p[i][2] < p[j][2] }\nfunc (p Heap) Swap(i, j int) { p[i], p[j] = p[j], p[i] }\nfunc (p *Heap) Push(i interface{}) { *p = append(*p, i.([]int)) }\nfunc (p *Heap) Pop() interface{} { v := (*p)[len(*p)-1]; *p = (*p)[:len(*p)-1]; return v }\n``` | 0 | 0 | ['Heap (Priority Queue)', 'Go'] | 0 |
maximum-building-height | [Python] Beats 100%, sort + one pass solution, O(nlog(n)) | python-beats-100-sort-one-pass-solution-mdpys | I have I think a pretty unique solution, using a single-pass approach to find the max height.\n\nThe main idea of the solution is to "follow the path" of maximu | skasch | NORMAL | 2021-12-11T22:56:39.213429+00:00 | 2021-12-11T22:56:39.213466+00:00 | 263 | false | I have I think a pretty unique solution, using a single-pass approach to find the max height.\n\nThe main idea of the solution is to "follow the path" of maximum building heights by iterating over the most restrictive restrictions along the indexes.\n\nIf we are at a given restriction `i1, h1`, then we can look at all the following restrictions and find the one that will restrict the most our building heights following this position. The one that will restrict the most the height is the one `i2, h2` such that `i2 + h2` is minimal.\n\n```\n5\n4 4 X\n3 X X 2\n2 1 X\n1 3\n0\n 1 2 3 4 5 6 7 8 9\ni1 = 3, h1 = 2\ni2 = 7, h2 = 3\ni3 = 8, h3 = 1\ni4 = 4, h4 = 4\n```\n\nIn that example, `i3, h3` is more restrictive than `i2, h2`. The good news is, we can easily find the next most restrictive restriction by sorting them by `i + h`.\n\nWe also need to add the first restriction, `1, 0`, as well as handle the case where the restriction does not apply.\n\nIn the previous example, even though `i4 + h4` is lower than `i3 + h3`, we do not consider it because it is "above" the line starting fro `i1 + h1`. In practice, that means skipping restrictions such that `h4 - i4 (0) >= h1 - i1 (-1)`.\n\nGiven `i1, h1` and `i2, h2`, we want to compute the maximum height of the buildings between these. A bit of maths gives us the intersection between the two following lines:\n\n`y = (h1 - i1) + x`\n`y = (h2 + i2) - x`\n\nSolving this equation gives us `y = (h1 + h2 + i2 - i1) / 2`. Because we\'re interested in integer solutions, we can take the integer division by 2.\n\nWithout further ado, the code itself:\n\n```py\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n if not restrictions:\n return n - 1\n restrictions.append([1, 0]) # Add the restriction for the initial position\n restrictions.sort(key=lambda x: x[1] + x[0]) # Sort by increasing i + h\n idx = 0 # The index in the restrictions array\n max_height = 0\n while idx < len(restrictions):\n pos, h = restrictions[idx]\n idx += 1\n while idx < len(restrictions) and restrictions[idx][1] - restrictions[idx][0] >= h - pos:\n\t\t\t\t# skip the next restriction if it is "above" the line starting from the current one\n idx += 1\n if idx == len(restrictions):\n\t\t\t\t# Handles the last restriction: fill the line until the last position at n\n max_height = max(max_height, h + n - pos)\n break\n next_pos, next_h = restrictions[idx]\n\t\t\t# A bit of maths gives us the formula for the maximum height between two consecutive\n\t\t\t# restrictions\n max_height = max(max_height, (h + next_h + next_pos - pos) // 2)\n return max_height\n``` | 0 | 0 | ['Sorting', 'Python', 'Python3'] | 0 |
maximum-building-height | Will this solution work for N ~ 1e7 Passing 36/50 Cases | will-this-solution-work-for-n-1e7-passin-0qwr | I have tried to calculate the max_possible_height for all buildings based on the restrictions given .then using the cur_height variable which increments by 1 be | stunnareeb_09 | NORMAL | 2021-06-11T12:13:49.734083+00:00 | 2021-06-11T12:13:49.734125+00:00 | 138 | false | I have tried to calculate the max_possible_height for all buildings based on the restrictions given .then using the `cur_height` variable which increments by 1 between adjacent buildings have calculated the actual possible height `actual_height` which can be attained , then their are chances that the current possible height of the building may be greater than the previous one by more than 1 in that case I have changed the height of the previous buildings accordingly (depending upon the height of the current building ) .\n```\nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& a) {\n if(a.size() == 0 )\n {\n return n-1;\n }\n for(auto &u : a)\n {\n u[0]--;\n }\n sort(a.begin() , a.end() , [&]( const vector <int> &p1 , const vector <int> &p2 )\n {\n return p1[0] < p2[0];\n }\n );\n \n vector <int > max_possible_height( n , -1 ) ,actual_height( n );\n for( auto u : a )\n {\n int idx = u[0] , val = u[1];\n /// cout << " for current idx and val as : " << idx << " " << val << endl;\n while ( idx >= 0 and ( max_possible_height[idx] == -1 ) )\n {\n max_possible_height[ idx ] = val;\n val++;\n idx--;\n }\n /* cout << " current max_possible_height is : \\n";\n for( auto u : max_possible_height )\n {\n cout << u << " ";\n }*/\n }\n //cout << endl;\n if(a.size()){\n int idx = a[ a.size() - 1 ][ 0 ] , val = a[ a.size()-1 ] [ 1 ];\n idx++ , val++;\n while( idx < n and ( max_possible_height[idx] == -1 ) )\n {\n max_possible_height[ idx ] = val;\n val++;\n idx++;\n }\n }\n \n int cur_height = 0 ;\n for( int i = 0 ; i < n ;i++ )\n {\n if( cur_height <= max_possible_height[i] )\n {\n actual_height[i] = cur_height;\n cur_height++;\n }\n else\n {\n actual_height[i] = max_possible_height[i];\n cur_height = actual_height[i]+1;\n }\n }\n for( int i = n - 2 ; i >= 0 ; i-- )\n {\n if ( ( actual_height[i] > actual_height[i+1] ) and actual_height[i] - actual_height[i+1] > 1 )\n {\n actual_height[i] =actual_height[i+1] + 1 ; \n }\n }\n for( auto u : actual_height )\n {\n cout << u << " ";\n }\n cout << endl;\n int ans =0 ;\n for(auto u : actual_height) ans = max(ans , u );\n return ans;\n }\n};\n``` | 0 | 0 | [] | 1 |
maximum-building-height | From O(n) to O(mlgm) Two Solutions | from-on-to-omlgm-two-solutions-by-xu_daf-lf3i | \nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n \'\'\'\n # O(n), TLE/MLE\n # Each buliding is | xu_dafang | NORMAL | 2021-05-25T23:58:59.731857+00:00 | 2021-05-25T23:58:59.731898+00:00 | 287 | false | ```\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n \'\'\'\n # O(n), TLE/MLE\n # Each buliding is restricted from left and right. Thus, update the height of the building from left to right and then from right to left\n H = [float("inf") for _ in range(n)]\n H[0] = 0\n for id, h in restrictions:\n H[id - 1] = h\n for i in range(1, n):\n if H[i] >= H[i] - 1:\n H[i] = min(H[i], H[i - 1] + 1)\n mx = H[n - 1]\n for i in range(n - 2, -1, -1):\n if H[i] >= H[i + 1]:\n H[i] = min(H[i], H[i + 1] + 1)\n mx = max(mx, H[i])\n return mx\n \'\'\'\n \'\'\'\n Example:\n n = 10, restrictions = [[5,3],[2,5],[7,4],[10,3]]\n H = [0, 5, inf, inf, 3, inf, 4, inf, inf, 3]\n from left to right: H = [0, 1, 2, 3, 3, 4, 4, 5, 6, 3]\n from right to left: H = [0, 1, 2, 3, 3, ,4, 4 , 5, 4, 3]\n \'\'\'\n \'\'\'\n Actually, the highest is bounded by restrictions, we can only consider the restrictions\n Consider two restrictions (id1, h1) and (id2, h2) where id1 < id2. Also assume h1 < h2 (because of symmetry)\n What is the highest building between id1 and id2 (inclisive) ?\n Solution:\n 1: First of all, make sure the restrictions are consistent. Two restrictions are consistent if monotonically increasing from the lower one to the higher one won\'t exceed the higher one. For example, [1, 2] and [2, 5] are inconsistent while [1, 2] and [2, 3] are consistent.\n 2: Keep increasing from id1 and then decreasing somewhere until id2. Specifically, start from id1, find the k where from id1 to id1 + k, the height is monotonically increasing and from id1 + k + 1 to id2, the height is monotonically decreasing\n h[id1 + k] = h1 + k (1)\n h[id1 + k] = h2 + (id2 - (id1 + k)) (2)\n from (1) and (2) h1 + k = h2 + id2 - id1 - k ==> k = (h2 + id2 - id1 - h1)/2 ==> highest = h1 + k = (h2 + h1 + id2 - id1)/2\n \n For example1, two restrictions [3, 5] and [9, 7]\n height 5 6 7 8 9 8 7 \n idx 3 4 5 6 7 8 9\n highest = (5 + 7 + 9 - 3)/2 = (12 + 6)/2 = 9 \n \n For example2, , two restrictions [3, 5] and [9, 11]\n height 5 6 7 8 9 10 11 \n idx 3 4 5 6 7 8 9\n highest = (5 + 11 + 9 - 3)/2 = (16 + 6)/2 = 11\n \n For example3, two restrictions [3, 10] and [9, 6]\n height 10 11 10 9 8 7 6 \n idx 3 4 5 6 7 8 9\n highest = (6 + 10 + 9 - 3)/2 = (16 + 6)/2 = 11\n \'\'\'\n # m = len(restrictions), O(mlogm) time and O(1) space\n m = len(restrictions)\n if not restrictions:\n return n - 1\n restrictions.sort()\n \n # Make the restrictions consistent\n id1, h1 = 1, 0\n for i in range(m):\n id2, h2 = restrictions[i]\n h2 = min(h2, h1 + id2 - id1)\n restrictions[i] = [id2, h2]\n id1, h1 = id2, h2\n id1, h1 = restrictions[m - 1]\n for i in range(m - 2, -1, -1):\n id2, h2 = restrictions[i]\n h2 = min(h2, h1 + id1 - id2)\n restrictions[i] = [id2, h2]\n id1, h1 = id2, h2\n \n # Update the highest building\n mx = 0\n id1, h1 = 1, 0\n for id2, h2 in restrictions:\n mx = max(mx, (h1 + h2 + id2 - id1)//2)\n # print(id1, id2, mx)\n h1, id1 = h2, id2\n #print(mx)\n # now consider the gap between the last index of restrictions and the n-th building\n if restrictions[-1][0] < n:\n mx = max(mx, h1 + (n - restrictions[-1][0]))\n return mx\n\n\'\'\'\n2\n[[2,0]]\n6\n[]\n5\n[[2,1],[4,1]]\n10\n[[5,3],[2,5],[7,4],[10,3]]\n12\n[[5,3],[2,5],[7,4],[10,3], [11, 12]]\n\'\'\'\n\n``` | 0 | 0 | [] | 0 |
maximum-building-height | Python3 easy to understand | python3-easy-to-understand-by-randomrock-2u3y | \nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n res = restrictions + [[1,0]] # for ease of processing, sett | RandomRock | NORMAL | 2021-05-17T22:12:27.097400+00:00 | 2021-05-17T22:15:11.831430+00:00 | 264 | false | ```\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n res = restrictions + [[1,0]] # for ease of processing, setting a 0-height restraint for the first building\n res = sorted(res, key=lambda x:x[0])\n if res[-1][0] != n:\n res += [[n, float(\'inf\')]] # for ease of processing, setting a free restraint for the last building\n\n # scan left -> right to correct the unfeasible restraints\n for i in range(0, len(res)-1, 1):\n dist = abs(res[i][0] - res[i+1][0]) # distance between the two restrained buildings\n if res[i + 1][1] > res[i][1] + dist:\n res[i + 1][1] = res[i][1] + dist\n \n # scan right -> left to correct the unfeasible restraints\n for i in range(len(res)-1, 0, -1):\n dist = abs(res[i-1][0] - res[i][0]) # distance between the two restrained buildings\n if res[i - 1][1] > res[i][1] + dist:\n res[i - 1][1] = res[i][1] + dist\n\n # use math to find the heighest building under current restraints\n mbh = 0\n for i in range(len(res)-1):\n dist = abs(res[i][0] - res[i+1][0])\n diff = abs(res[i][1] - res[i+1][1])\n if diff > dist:\n mbh = max(mbh, max(res[i+1][1], res[i][1])) # best height is the constraint\n else:\n mbh = max(mbh, (dist + res[i][1] + res[i+1][1]) // 2) # best height is in between two constraints\n\n return mbh\n``` | 0 | 0 | [] | 0 |
maximum-building-height | Python3 O(NlogN) | python3-onlogn-by-xy_nu-zu19 | \nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n if not restrictions:\n return n-1\n resi | xy_nu | NORMAL | 2021-05-17T05:51:02.722975+00:00 | 2021-05-17T05:51:02.723008+00:00 | 176 | false | ```\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n if not restrictions:\n return n-1\n resi = sorted(restrictions, key = lambda x:x[0])\n \n # update resi\n k = 0\n idx = 1\n for resii in resi:\n resii[1] = min(resii[1], k+resii[0]-idx)\n k = resii[1]\n idx = resii[0]\n k = resi[-1][1]\n idx = resi[-1][0]\n resi.reverse()\n for resii in resi[1:]:\n resii[1] = min(resii[1], k-resii[0]+idx)\n k = resii[1]\n idx = resii[0]\n resi.reverse()\n \n f = 0\n idx = 1\n res = 0\n for resii in resi:\n ff = min(f+resii[0]-idx, resii[1])\n res = max(res, (resii[0]-idx+f+ff)//2)\n idx = resii[0]\n f = ff\n\n return max(f+n-idx,res)\n \n \n``` | 0 | 0 | [] | 0 |
maximum-building-height | [ruby] O(n) solution | ruby-on-solution-by-tuang3142-d1pq | Idea\n\nThanks votrubac for the original idea\nGoing from left to right, let\'s find the maximum height h between two limits: h1 and h2 which are indexed i and | tuang3142 | NORMAL | 2021-05-15T03:31:51.856691+00:00 | 2021-05-15T03:39:58.143310+00:00 | 141 | false | **Idea**\n\n[Thanks votrubac for the original idea](https://leetcode.com/problems/maximum-building-height/discuss/1175269/C%2B%2B-with-picture-2-passes)\nGoing from left to right, let\'s find the maximum height `h` between two limits: `h1` and `h2` which are indexed `i` and `j`.\nTo get the highest result from `h1`, we keep increasing the height by 1 from `i` to `j`. At best, `h = h1 + (j - i)`.\nIf `h <= h2`: decrease h2 to meet h (`h2 = h`) since it\'s no help keeping it higher.\nIf `h > h2`: find a mutual "top" so we can ascend to that point and descend to h2: `h = (h + h2) / 2`.\nRepeat from right to left and update the answer.\n\n **Complexity**\n \n- Time & Space: `O(n)`\n \n**Code**\n\n```ruby\ndef get_max_height(cap, i, j)\n i1, h1 = cap[i]\n i2, h2 = cap[j]\n\n h = h1 + (i2 - i1).abs\n\n h <= h2 ? cap[j][1] = h : (h + h2) / 2\nend\n\ndef max_building(n, cap)\n cap.concat [[1, 0], [n, n - 1]]\n cap.sort!\n size = cap.size\n\n 0.upto(size - 2).map { |i| get_max_height(cap, i, i + 1) }\n (size - 1).downto(1).map { |i| get_max_height(cap, i, i - 1) }.max\nend\n``` | 0 | 0 | [] | 1 |
maximum-building-height | Java O(NlogN) 42ms 100% solution: | java-onlogn-42ms-100-solution-by-jasonz2-aj3q | Sort the restricitons and then trim from the right side.\n2. Iterate the trimmed restrictions from left to right, and find out he maximum height.\n3. Make sure | jasonz2020 | NORMAL | 2021-05-04T14:59:54.030817+00:00 | 2021-05-04T15:03:17.730219+00:00 | 373 | false | 1. Sort the restricitons and then trim from the right side.\n2. Iterate the trimmed restrictions from left to right, and find out he maximum height.\n3. Make sure to check `id = n` at the end, it might also be a possible maximum height.\n\n```\nclass Solution {\n public int maxBuilding(int n, int[][] restrictions) {\n if (restrictions.length == 0) return n - 1;\n int m = restrictions.length;\n \n Arrays.sort(restrictions, (a, b) -> a[0] - b[0]);\n \n for (int i = m - 2; i >= 0; i--) {\n restrictions[i][1] = Math.min(restrictions[i][1],\n restrictions[i + 1][1] + restrictions[i + 1][0] - restrictions[i][0]);\n } // Trim the restrictions from right to left \n \n int id = 1, height = 0; // Used for recording previous restriction id and height\n int res = 0; \n \n for (int[] r : restrictions) {\n int currMax = 0;\n if (r[1] >= height + r[0] - id) {\n currMax = height + r[0] - id;\n height = currMax;\n } else {\n currMax = (height + r[0] - id + r[1]) / 2;\n height = r[1];\n }\n id = r[0]; \n res = Math.max(res, currMax);\n }\n \n // if n is not a restriction id, it could potentially be a max height\n if (id != n) res = Math.max(res, height + n - id); \n \n return res;\n }\n}\n```\n | 0 | 0 | ['Java'] | 0 |
maximum-building-height | C# 2 passes | c-2-passes-by-rade-radumilo-ha8l | This is a C# variation of votrubac\'s solution in C++ (LINK). I didn\'t want to hustle with sorting of jagged arrays and like, so I have created a small class B | rade-radumilo | NORMAL | 2021-04-29T18:32:21.083633+00:00 | 2021-04-29T18:32:21.083674+00:00 | 144 | false | This is a C# variation of votrubac\'s solution in C++ ([LINK](https://leetcode.com/problems/maximum-building-height/discuss/1175269/C%2B%2B-with-picture-2-passes)). I didn\'t want to hustle with sorting of jagged arrays and like, so I have created a small class `Building` and `List<Building>`.\n\n```\npublic class Building : IComparable {\n public int idx {get; set;}\n public int hgt {get; set;}\n\n public Building(int i, int h) {\n idx = i;\n hgt = h;\n }\n\n public int CompareTo(object obj) {\n if (obj is null) return 1;\n\n Building other = obj as Building;\n \n if (this.idx > other.idx) return 1;\n if (this.idx < other.idx) return -1;\n\n return 0;\n }\n}\n\npublic class Solution {\n public int MaxBuilding(int n, int[][] restrictions) {\n \n if (n < 2) return 0;\n if (restrictions.Length < 1) return n-1;\n \n int max_height = 0;\n \n List<Building> actual_heights = new List<Building>();\n \n actual_heights.Add(new Building(1, 0));\n \n for (int i = 0; i < restrictions.Length; i++) {\n actual_heights.Add(new Building(restrictions[i][0], restrictions[i][1]));\n }\n \n actual_heights.Add (new Building(n, n-1));\n \n actual_heights.Sort();\n \n for (int i = 0; i < actual_heights.Count - 1; i++) {\n Building building1 = actual_heights[i];\n Building building2 = actual_heights[i+1];\n \n int h1 = building1.hgt;\n int h2 = building2.hgt;\n int h = h1 + Math.Abs(building2.idx - building1.idx);\n \n if (h > h2) {\n h = h2 + (h - h2) / 2;\n }\n \n building2.hgt = Math.Min(h, h2);\n }\n \n actual_heights.Sort((a, b) => b.CompareTo(a));\n \n for (int i = 0; i < actual_heights.Count - 1; i++) {\n Building building1 = actual_heights[i];\n Building building2 = actual_heights[i+1];\n \n int h1 = building1.hgt;\n int h2 = building2.hgt;\n int h = h1 + Math.Abs(building2.idx - building1.idx);\n \n if (h > h2) {\n h = h2 + (h - h2) / 2;\n }\n \n max_height = Math.Max(max_height, h);\n \n building2.hgt = Math.Min(h, h2);\n }\n \n return max_height;\n }\n}\n``` | 0 | 0 | [] | 0 |
maximum-building-height | Java Faster Than 97.97% O(NLogN) | java-faster-than-9797-onlogn-by-sunnydho-tz2t | ```\n\tpublic int maxBuilding(int n, int[][] res) {\n int size= res.length;\n if(size == 0) return n - 1;\n int[] realHeight= new int[size] | sunnydhotre | NORMAL | 2021-04-29T06:39:49.774675+00:00 | 2021-04-29T06:39:49.774703+00:00 | 197 | false | ```\n\tpublic int maxBuilding(int n, int[][] res) {\n int size= res.length;\n if(size == 0) return n - 1;\n int[] realHeight= new int[size];\n Arrays.sort(res,(a,b)->a[0]-b[0]);\n realHeight[0]= Math.min(res[0][0]-1,res[0][1]);\n for(int i=1; i<size; i++){\n realHeight[i]= Math.min(res[i][1], realHeight[i-1] + res[i][0] - res[i-1][0]);\n }\n for(int i=size - 2; i >= 0; i--){\n realHeight[i]= Math.min(realHeight[i], realHeight[i+1] + res[i+1][0] - res[i][0]);\n }\n int maxHeight= realHeight[0] + (res[0][0] - 1 - realHeight[0]) / 2;\n maxHeight= Math.max(maxHeight, realHeight[size-1] + n - res[size-1][0]);\n for(int i=1; i<size; i++){\n int dist= res[i][0] - res[i-1][0];\n int greaterBuilding= Math.max(realHeight[i],realHeight[i-1]);\n int heightDiff= Math.abs(realHeight[i] - realHeight[i-1]);\n int distBetweenEqualHeightBuildings= dist - heightDiff;\n maxHeight= Math.max(maxHeight, greaterBuilding + distBetweenEqualHeightBuildings / 2);\n }\n return maxHeight;\n } | 0 | 0 | [] | 0 |
maximum-building-height | C# 608ms solution, achieved by removing restrictions | c-608ms-solution-achieved-by-removing-re-xssx | The innovation here vs other posters is that if we find a restriction that isn\'t actually reachable, it\'s essentially a no-op.\n\nConsider the case:\n10\n[[3, | rollie42 | NORMAL | 2021-04-27T12:14:36.166179+00:00 | 2021-04-27T12:14:36.166205+00:00 | 106 | false | The innovation here vs other posters is that if we find a restriction that isn\'t actually reachable, it\'s essentially a no-op.\n\nConsider the case:\n10\n[[3,1],[4,5]]\n\nIf we know index 3 can\'t be above 1, we can tell that index 4 can\'t be above 2; having a rule saying it can\'t be above 5 is a no-op, and can be removed, simplifying subsequent iterations.\n\nThe below is rather verbose and not optimized, but hopfully easy to understand :)\n\n```\npublic class Solution {\n\n public class Restriction {\n public int index;\n public int height;\n\n public Restriction(int[] r)\n {\n // let\'s adjust index to be 0-based\n index=r[0]-1;\n height=r[1];\n }\n\n public Restriction(int index, int height)\n {\n this.index = index;\n this.height = height;\n }\n }\n\n public (LinkedListNode<Restriction>, LinkedListNode<Restriction>) getLowHigh(LinkedListNode<Restriction> restriction) {\n var next = restriction.Next;\n return restriction.Value.height < next.Value.height ? (restriction, next) : (next, restriction); \n }\n\n public int MaxBuilding(int n, int[][] _restrictions) {\n IEnumerable<Restriction> r = _restrictions\n .Select(r => new Restriction(r))\n .OrderBy(r => r.index)\n .Prepend(new Restriction(0, 0)); // sentinal\n\n // Supports removing elements in O(1)\n var restrictions = new LinkedList<Restriction>(r);\n\n var node = restrictions.First;\n while(node?.Next != null) {\n var (lowNode, highNode) = getLowHigh(node);\n var (low, high) = (lowNode.Value, highNode.Value);\n var dd = Math.Abs(high.index - low.index);\n var dh = high.height - low.height;\n if (dh >= dd) {\n // Our difference in height is higher than our distance; we can never *reach* high.height,\n // so it\'s effectively a no-op\n\n // If we are removing the current node, adjust node; else just re-evaluate vs the new \'next\'\n if (node == highNode) node = node.Previous ?? node.Next;\n restrictions.Remove(highNode);\n } else {\n node = node.Next;\n }\n }\n\n // This default is the value from the last entry until the end of the buildings\n var max = restrictions.Last.Value.height + (n - restrictions.Last.Value.index - 1);\n node = restrictions.First;\n\n while(node?.Next != null) {\n var (lowNode, highNode) = getLowHigh(node);\n var (low, high) = (lowNode.Value, highNode.Value);\n var dd = Math.Abs(high.index - low.index);\n var dh = high.height - low.height;\n var freeSteps = dd - dh;\n var localMax = high.height + freeSteps / 2;\n max = Math.Max(max, localMax);\n node = node.Next;\n }\n\n return max;\n }\n}\n``` | 0 | 0 | [] | 0 |
maximum-building-height | simple method | simple-method-by-chandankr0699-w02b | class Solution {\n public int maxBuilding(int n, int[][] restrictions) {\n int ans[]=new int[n+1];\n ans[0]=0;\n ans[1]=0;\n for( | chandankr0699 | NORMAL | 2021-04-27T10:41:23.547451+00:00 | 2021-04-27T10:41:23.547484+00:00 | 156 | false | class Solution {\n public int maxBuilding(int n, int[][] restrictions) {\n int ans[]=new int[n+1];\n ans[0]=0;\n ans[1]=0;\n for(int i=2;i<=n;i++){\n ans[i]=i-1;\n }\n for(int i=0;i<restrictions.length;i++){\n ans[restrictions[i][0]]=Math.min(ans[restrictions[i][0]],restrictions[i][1]);\n }\n int res=ans[1];\n for(int i=2;i<=n;i++){\n ans[i]=Math.min(ans[i],ans[i-1]+1);\n }\n for(int i=n-1;i>1;i--){\n ans[i]=Math.min(ans[i],ans[i+1]+1);\n }\n for(int i=2;i<=n;i++){\n res=Math.max(res,ans[i]);\n }\n return res;\n }\n} | 0 | 0 | [] | 1 |
maximum-building-height | C# | O(r log r) | with link to explanation | c-or-log-r-with-link-to-explanation-by-c-luu9 | I couldn\'t solve this during contest tried with dp approach and failed by considering only one pass, but this needs consideration from both sides. \n\nThis is | crackthebig | NORMAL | 2021-04-27T05:49:03.266621+00:00 | 2021-04-27T05:49:03.266655+00:00 | 101 | false | I couldn\'t solve this during contest tried with dp approach and failed by considering only one pass, but this needs consideration from both sides. \n\nThis is the C# implementation of solution given by @votrubac [here](https://leetcode.com/problems/maximum-building-height/discuss/1175269/C%2B%2B-with-picture-2-passes)\n\n```\npublic class Solution {\n public int MaxBuilding(int n, int[][] restrictions) {\n IList<int[]> r = new List<int[]>();\n foreach(var restriction in restrictions)\n r.Add(restriction);\n //sentinal ids\n r.Add(new [] {1, 0});\n r.Add(new [] {n , n-1}); \n r = r.OrderBy(x=>x[0]).ToList();\n \n ApplyRestrictions(r);\n \n r = r.Reverse().ToList();\n return ApplyRestrictions(r);\n }\n \n public int ApplyRestrictions(IList<int[]> r)\n {\n int maxHeight = 0;\n int n = r.Count;\n \n for(int i=1; i<n; i++){\n int h1 = r[i-1][1], h2 = r[i][1];\n int h = h1 + Math.Abs(r[i-1][0] - r[i][0]);\n \n if(h > h2)\n h = h2 + (h - h2) / 2 ;\n maxHeight = Math.Max(maxHeight, h);\n r[i][1] = Math.Min(h, h2);\n }\n return maxHeight;\n }\n}\n``` | 0 | 0 | [] | 0 |
maximum-building-height | O(nlog(n)) might be fastest Python solution(1856 ms) ( guess how will it be in C++)? | onlogn-might-be-fastest-python-solution1-c7b3 | \nThe restrictions might be too high, so we need cut it lower.\nTo do it, we go from left to right and then right to left.\nWhen do from left to right, [1,0] is | yjyjyj | NORMAL | 2021-04-26T16:54:03.688151+00:00 | 2021-04-26T16:58:15.076594+00:00 | 101 | false | \nThe restrictions might be too high, so we need cut it lower.\nTo do it, we go from left to right and then right to left.\nWhen do from left to right, [1,0] is added as the inital, that is a fact.\nWhen do from right to left, [n + 1, X] is added as the inital.\nThat X is the highestt possible of n building. Which is calculatable from the last building in the updated restrictions array.\n\nAnd we got the excat highest possibility of the buildings who show up in the restrictions array.\nThen we go through the restriction for each pair of the buildings shows up in the restrictions array. And calculate the highest building between them.\n\nThese are O(N)\nwhile to sort restrictions array is O(Nlog(N))\n\n```\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n if not restrictions:\n return n - 1\n ans = 0\n def leftward(prev, next):\n return [next[0], min(next[1], prev[1] + next[0] - prev[0])]\n def rightward(prev, next):\n nonlocal ans\n next = [next[0], min(next[1], prev[1] + prev[0] - next[0])]\n high, low = sorted([prev[1], next[1]])\n ans = max(ans, high + (prev[0] - next[0] - high + low) // 2)\n return next\n restrictions = list(accumulate(sorted(restrictions), leftward, initial=[1,0]))\n for _ in accumulate(restrictions[::-1], rightward, initial=[n + 1, n - restrictions[-1][0] + restrictions[-1][1]]):\n pass\n return ans \n \n``` | 0 | 0 | [] | 0 |
maximum-building-height | [Rust] two-pass solution | rust-two-pass-solution-by-grokus-uy2l | ```\n pub fn max_building(n: i32, a: Vec>) -> i32 {\n let mut a = a;\n a.extend_from_slice(&vec![vec![1, 0], vec![n, n - 1]]);\n a.sort_ | grokus | NORMAL | 2021-04-25T19:11:24.269913+00:00 | 2021-04-25T19:11:24.269953+00:00 | 76 | false | ```\n pub fn max_building(n: i32, a: Vec<Vec<i32>>) -> i32 {\n let mut a = a;\n a.extend_from_slice(&vec![vec![1, 0], vec![n, n - 1]]);\n a.sort_by(|x, y| x[0].cmp(&y[0]));\n let mut res = 0;\n for i in (0..a.len() - 1).rev() {\n a[i][1] = a[i][1].min(a[i + 1][1] + a[i + 1][0] - a[i][0]);\n }\n for i in 1..a.len() {\n a[i][1] = a[i][1].min(a[i - 1][1] + a[i][0] - a[i - 1][0]);\n let x = a[i][0] - a[i - 1][0] + (a[i][1] - a[i - 1][1]).abs();\n res = res.max(x / 2 + a[i][1].min(a[i - 1][1]));\n }\n res\n }\n | 0 | 0 | [] | 0 |
maximum-building-height | [Kotlin] Greedy solution | O(n logn) | kotlin-greedy-solution-on-logn-by-trinha-gzy4 | \nclass Solution {\n fun maxBuilding(n: Int, restrictions: Array<IntArray>): Int {\n var sorted: MutableList<IntArray> = restrictions.toMutableList()\ | trinhan-nguyen | NORMAL | 2021-04-25T18:40:52.457151+00:00 | 2021-04-25T18:40:52.457197+00:00 | 50 | false | ```\nclass Solution {\n fun maxBuilding(n: Int, restrictions: Array<IntArray>): Int {\n var sorted: MutableList<IntArray> = restrictions.toMutableList()\n sorted.add(intArrayOf(1, 0))\n sorted.add(intArrayOf(n, n - 1))\n sorted.sortBy { it.first() }\n \n for (i in 1..sorted.lastIndex) {\n val (curId, curRestriction) = sorted[i]\n val (prevId, prevRestriction) = sorted[i - 1]\n sorted[i][1] = Math.min(curRestriction, prevRestriction + curId - prevId) \n }\n \n for (i in sorted.lastIndex downTo 1) {\n val (curId, curRestriction) = sorted[i - 1]\n val (nextId, nextRestriction) = sorted[i]\n sorted[i - 1][1] = Math.min(curRestriction, nextRestriction + nextId - curId)\n }\n \n var res = 0\n for (i in 1..sorted.lastIndex) {\n val (curId, curRestriction) = sorted[i]\n val (prevId, prevRestriction) = sorted[i - 1]\n val up = (curId - prevId - Math.abs(curRestriction - prevRestriction)) / 2\n res = Math.max(res, Math.max(prevRestriction, curRestriction) + up)\n }\n return res\n }\n}\n```\nTime complexity: O(n logn)\nSpace complexity: O(n) | 0 | 0 | [] | 0 |
maximum-building-height | Simple Javascript with 2 loops and O(NlogN) based on restrictions | simple-javascript-with-2-loops-and-onlog-abyc | javascript\n/**\n * @param {number} n\n * @param {number[][]} restrictions\n * @return {number}\n */\nvar maxBuilding = function(n, restrictions) {\n if (restr | satanTime | NORMAL | 2021-04-25T17:25:08.465935+00:00 | 2021-04-25T18:07:00.002484+00:00 | 134 | false | ```javascript\n/**\n * @param {number} n\n * @param {number[][]} restrictions\n * @return {number}\n */\nvar maxBuilding = function(n, restrictions) {\n if (restrictions.length === 0) {\n return n - 1;\n }\n \n // Let\'s sort restrictions by block positions.\n // Then we won\'t meet surprises in the middle of loops.\n restrictions.sort((a, b) => a[0] - b[0]);\n\n // The idea is that we collect rays.\n // A left ray (it grows from left to right with a step of 1)\n // A right ray (it grows from right to left with a step of 1)\n // Their intersection is the point of the highest possible building.\n // For simplicity, we collect numbers of blocks where rays start (their height is 0 at those blocks).\n // [1, 3]\n // 1 - means that the left ray starts in the 1s block (its height is 0)\n // 3 - means that the right ray starts in the 3rd block (its height is 0)\n // in the 2nd block the left ray has the height of 1.\n // the same happens with the right ray.\n // Also, the block #2 is their intersection, therefore the max allowed height here is 1.\n // [1, 5] - has the max height of 2.\n // the left ray is: in the 2nd block it has the height of 1, 3rd block = 2, 4th block = 3, 5th block = 4.\n // the right ray is: 4th block = 1, 3rd block = 2, 2nd block = 3, 1st block = 4.\n // their intersection is the 3rd block, therefore the max possible height here is 2.\n const rays = [];\n\n // the default left ray starts in the 1st block.\n let rayLeft = 1;\n\n // Let\'s find all rays.\n for (let i = 0; i < restrictions.length; i += 1) {\n // a right ray\'s root is its restrction block plus its height, because the step of the height change per block is 1.\n let restrictionRayRight = restrictions[i][0] + restrictions[i][1];\n rays.push([rayLeft, restrictionRayRight]);\n\n // now we need to check its left root.\n\t// it is its restriction block minus its height.\n let restrictionRayLeft = restrictions[i][0] - restrictions[i][1];\n\t// also we need to ensure, that the new left ray is stricter than the current one.\n\t// otherwise, we should use the current one.\n\t// the right ones will be adjusted later.\n if (restrictionRayLeft > rayLeft) {\n rayLeft = restrictionRayLeft;\n }\n }\n\n // an edge case. if the latest block doesn\'t have a restriction,\n // we are adding a right ray which is a mirror of the current left ray.\n if (rayLeft !== n) {\n rays.push([rayLeft, n + (n - rayLeft)]);\n }\n \n let result = 0;\n let local = 0;\n // let\'s check rays\n for (let i = rays.length - 1; i >= 0; i -= 1) {\n // because we know that 1 block can grow with 1 floor,\n // the max height is a right ray\'s block minus its left ray\'s block and devide by 2.\n local = Math.floor((rays[i][1] - rays[i][0]) / 2);\n if (local > result) {\n result = local;\n }\n\t\n\t// Let\'s adjust right rays, the stricter ray has priority.\n\tif (i !== 0 && rays[i - 1][1] > rays[i][1]) {\n rays[i - 1][1] = rays[i][1];\n }\n }\n\n return result;\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
maximum-building-height | C++ O(mlogm) 2 passes greedy solution with comments | c-omlogm-2-passes-greedy-solution-with-c-4ex5 | \nint maxBuilding(int n, vector<vector<int>>& restrictions) \n{\n\tint result=0;\n\tsort(restrictions.begin(),restrictions.end()); // sort by location\n\tint m= | eminem18753 | NORMAL | 2021-04-25T16:30:10.448862+00:00 | 2021-04-25T16:33:26.215202+00:00 | 79 | false | ```\nint maxBuilding(int n, vector<vector<int>>& restrictions) \n{\n\tint result=0;\n\tsort(restrictions.begin(),restrictions.end()); // sort by location\n\tint m=restrictions.size();\n\tfor(int i=0;i<m;i++) // from left to right\n\t\tif(i==0) restrictions[i]={restrictions[i][0],min(restrictions[i][1],restrictions[i][0]-1)}; // the height limit for first restricted house\n\t\telse restrictions[i]={restrictions[i][0],min(restrictions[i][1],restrictions[i-1][1]+restrictions[i][0]-restrictions[i-1][0])}; // the height limit for following restricted houses (eg. determined by the previous restricted houses)\n\n\tfor(int i=m-1;i>-1;i--) // from right to left\n\t\tif(i==m-1) restrictions[i]={restrictions[i][0],min(restrictions[i][1],restrictions[i][0]-1)}; // the height limit for last restricted house\n\t\telse restrictions[i]={restrictions[i][0],min(restrictions[i][1],restrictions[i+1][1]+restrictions[i+1][0]-restrictions[i][0])}; //the height limit for previous restricted houses (eg. determined by the next restricted house)\n\n\tfor(int i=0;i<m;i++) result=max(result,restrictions[i][1]); // the maximum height for restricted houses\n\n\trestrictions.insert(restrictions.begin(),{1,0}); // add the restriction for the first house\n\n\tfor(int i=0;i<m;i++) result=max(result,(restrictions[i][1]+restrictions[i+1][1]+restrictions[i+1][0]-restrictions[i][0])/2); // the maximum height for non-restricted houses\n\n\tresult=max(result,restrictions[m][1]+n-restrictions[m][0]); // the maximum height for the last house\n\treturn result;\n}\n``` | 0 | 0 | [] | 0 |
maximum-building-height | need help | need-help-by-krishnendra007-9epu | can anyone tell me why it is giving tle , its o(n) with two passes, using o(n) space\n\'\'\'\nclass Solution {\npublic:\n int maxBuilding(int n, vector>& res | krishnendra007 | NORMAL | 2021-04-25T16:05:43.146793+00:00 | 2021-04-26T10:59:56.093474+00:00 | 57 | false | can anyone tell me why it is giving tle , its o(n) with two passes, using o(n) space\n\'\'\'\nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& res) {\n vector<int> v(n+1,0);\n \n \n unordered_map<int,int>mp;\n for(int i=0;i<res.size();i++){\n mp[res[i][0]]=res[i][1];\n }\n \n \n int j=2;\n while(j<=n){\n if(mp.find(j)!=mp.end()){\n v[j]=min(v[j-1]+1,mp[j]);\n }\n else v[j]=v[j-1]+1;\n \n j++;\n }\n \n j=n-1;\n while(j>=1){\n v[j]=min(v[j],v[j+1]+1); \n j--;\n }\n \n return *max_element(v.begin(),v.end());\n \n }\n};\n\'\'\' | 0 | 1 | [] | 0 |
maximum-building-height | [Go] Time: O(m log m) / Space: O(1) with explanation | go-time-om-log-m-space-o1-with-explanati-l4it | Time complexity O(m log m) average bound by sort.Slice. Other ops are O(n)\nSpace O(1), various constants and temporary variables\n\nIntuition:\n\n n is too la | sebnyberg | NORMAL | 2021-04-25T13:29:11.485322+00:00 | 2021-04-25T13:34:41.936980+00:00 | 47 | false | Time complexity O(m log m) average bound by sort.Slice. Other ops are O(n)\nSpace O(1), various constants and temporary variables\n\nIntuition:\n\n* `n` is too large to create one element per building, so a list of only restricted buildings and their heights are needed\n* There is an implicit "restriction" that the first building has to be size 0, and the last building (possibly) has no restriction\n* Restrictions alone are not enough to determine the height. A building may become lower than its restriction due to nearby restrictions.\n* If the maximum possible height of each restricted building is known, it is relatively easy to calculate the maximum total height\n* The easiest way to find the max height for restricted buildings is to do a two-pass, once from left, then from right, keeping the min height as the "max possible" height\n* Once heights are known, the highest possible building is either a) one of the restricted buildings, or b) between two buildings\n* If the gap between two restricted buildings is bigger than their difference in height, it is possible to build higher buildings in-between\n* To reduce storage, re-use the restrictions array to represent the buildings\n\n```go\nconst (\n\tpos = 0\n\theight = 1\n)\n\nfunc maxBuilding(n int, restrictions [][]int) int {\n\t// Too annoying to type\n\tbuilds := restrictions\n\n\t// Add implicit restriction for the first building and sort by position\n\tbuilds = append(builds, []int{1, 0})\n\tsort.Slice(builds, func(i, j int) bool {\n\t\treturn builds[i][pos] < builds[j][pos]\n\t})\n\n\t// Add auxiliary last building if not part of the list already\n\tif builds[len(builds)-1][pos] != n {\n\t\tbuilds = append(builds, []int{n, n + 1})\n\t}\n\n\t// From left to right, calculate the height each building would have\n\t// if left unhindered by the right side\n\tfor i := range builds {\n\t\tif i == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tbuilds[i][height] = min(\n\t\t\tbuilds[i][height],\n\t\t\tbuilds[i-1][height]+builds[i][pos]-builds[i-1][pos],\n\t\t)\n\t}\n\n\t// Then from right to left\n\tnbuilds := len(builds)\n\tfor i := nbuilds - 2; i >= 0; i-- {\n\t\tbuilds[i][height] = min(\n\t\t\tbuilds[i][height],\n\t\t\tbuilds[i+1][height]+builds[i+1][pos]-builds[i][pos],\n\t\t)\n\t}\n\n\t// Heights of all buildings are correct according to restrictions\n\t// Iterate over pairs of buildings, checking if there is a long\n\t// gap that could be utilized to build higher than the restricted buildings\n\tmaxHeight := 0\n\tfor i := range builds {\n\t\tif i == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tmaxHeight = max(maxHeight, builds[i][height])\n\n\t\theightDiff := abs(builds[i][height] - builds[i-1][height])\n\t\tbuildingsBetween := builds[i][pos] - builds[i-1][pos] - 1\n\t\textra := buildingsBetween - heightDiff + 1\n\t\tif extra == 0 {\n\t\t\tcontinue\n\t\t}\n\t\t// there is a long gap between buildings, and it can be utilized to\n\t\t// build higher buildings\n\t\tmaxHeight = max(maxHeight, max(builds[i][height], builds[i-1][height])+extra/2)\n\t}\n\n\treturn maxHeight\n}\n``` | 0 | 0 | [] | 0 |
maximum-building-height | java sort | java-sort-by-516527986-bxgf | sort the restrictions;\nloop the restrictions from left to right \u3001 right to left then we get the right restrictions;\nat last , we can get the ans\n\ncl | 516527986 | NORMAL | 2021-04-25T12:27:37.010890+00:00 | 2021-04-25T12:27:37.010932+00:00 | 55 | false | sort the restrictions;\nloop the restrictions from left to right \u3001 right to left then we get the right restrictions;\nat last , we can get the ans\n```\nclass Solution {\n public int maxBuilding(int n, int[][] restrictions) {\n if(n == 0) return 0;\n if(restrictions == null || restrictions.length == 0){\n return n-1;\n }\n Arrays.sort(restrictions,(a,b)->(a[0]- b[0]));\n int len = restrictions.length;\n int preMaxTotal = 0;\n for(int i = 0 ; i < len ;i++){\n int idx = restrictions[i][0];\n if(i == 0){\n preMaxTotal = Math.min(restrictions[i][1] , idx-1);\n }else{\n preMaxTotal = Math.min(restrictions[i][1] , preMaxTotal + idx - restrictions[i-1][0]);\n }\n restrictions[i][1] = preMaxTotal;\n }\n for(int i = len-1 ; i >= 0 ;i--){\n int idx = restrictions[i][0];\n if(i == len-1){\n preMaxTotal = restrictions[i][1];\n }else{\n preMaxTotal = Math.min(restrictions[i][1] , preMaxTotal + restrictions[i+1][0] - idx);\n }\n restrictions[i][1] = preMaxTotal;\n }\n int ret = 0;\n for(int i = 0 ; i < len ; i++){\n ret = Math.max(ret , restrictions[i][1]);\n if(i == 0){\n ret = restrictions[i][1];\n }else{\n int idx = restrictions[i][0];\n int total = restrictions[i][1];\n int preIdx = restrictions[i-1][0];\n int preTotal = restrictions[i-1][1];\n if(Math.abs(total-preTotal) == idx - preIdx){\n ret = Math.max(ret , Math.max(total , preTotal));\n }else{\n ret = Math.max(ret , (idx - preIdx + preTotal + total)/2);\n }\n\n }\n }\n ret = Math.max(ret , restrictions[len-1][1] + n - restrictions[len-1][0]);\n return ret;\n }\n}\n``` | 0 | 0 | [] | 0 |
maximum-building-height | No Math Just Binary Search Simple CPP solution. nlogn | no-math-just-binary-search-simple-cpp-so-5170 | \nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& re) {\n vector<vector<long long int>> restrictions;\n for(auto it | user7634ri | NORMAL | 2021-04-25T08:05:26.531795+00:00 | 2021-04-25T08:05:26.531841+00:00 | 126 | false | ```\nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& re) {\n vector<vector<long long int>> restrictions;\n for(auto it:re) {\n restrictions.push_back({it[0],it[1]});\n }\n restrictions.push_back({1,0});\n \n sort(restrictions.begin(),restrictions.end());\n if((restrictions.back())[0]!=n) {\n restrictions.push_back({n,2000000000});\n }\n long long int ans=0;\n for(int i=restrictions.size()-2;i>=0;i--) {\n restrictions[i][1]=min(restrictions[i][1],restrictions[i+1][1]+restrictions[i+1][0]-restrictions[i][0]);\n }\n for(int i=0;i<restrictions.size()-1;i++) {\n \n long long int s=restrictions[i][0],e=restrictions[i+1][0];\n long long int h1=restrictions[i][1],h2=restrictions[i+1][1];\n //cout<<s<<" "<<e<<" "<<h1<<" "<<h2<<endl;\n long long int p=min(h1,h2);\n long long int q=max(h1,h2);\n long long int st=0,en=2e9;\n \n while(st<=en) {\n \n long long int m=(st+en)/2;\n long long int d1=max(0LL,m-p);\n long long int d2=max(0LL,m-q);\n if(d1+d2<=(e-s)) {ans=max(ans,m); st=m+1;}\n else {en=m-1;}\n \n }\n //cout<<ans<<endl;\n restrictions[i+1][1]=min(restrictions[i+1][1],restrictions[i][1]+restrictions[i+1][0]-restrictions[i][0]);\n \n }\n return ans;\n }\n};\n``` | 0 | 1 | [] | 0 |
maximum-building-height | [JavaScript] DP with explanation | javascript-dp-with-explanation-by-jialih-3qpt | Referenced solution from here: https://leetcode.com/problems/maximum-building-height/discuss/1175026/Java-DP-O(mlogm)\n\n- Step1: find the max at each restricte | jialihan | NORMAL | 2021-04-25T06:09:42.990761+00:00 | 2021-04-25T06:09:42.990790+00:00 | 145 | false | Referenced solution from here: https://leetcode.com/problems/maximum-building-height/discuss/1175026/Java-DP-O(mlogm)\n\n- Step1: find the max at each restricted index - `dp[m]`\n\t- left: `dp[i] = Min(dp[i-1] + (interval of building at index i & i-1 ), current_restricted_height)`\n\t- right: `dp[i] = Min(dp[i], dp[i+1] + (interval of building at index i & i+1) );`\n- Step2: find the max height of all building\n\t- Initial max value: (the height of first restricted building) & (the height of last restricted until the end).\n\t- How to calculate the heighest between `restriction[i-1][0] & restriction[i][0]`?\n\t\tJust use math to calculate:\n\t\t<img src="https://assets.leetcode.com/users/images/69d1795f-d015-44ec-8edc-281b639577b2_1619330683.570113.png" width="313" />\n\nJavaScript code:\n\n```js\nvar maxBuilding = function(n, restrictions) {\n var m = restrictions.length;\n if(!m)\n {\n return n-1;\n }\n restrictions.sort((a,b)=>a[0]-b[0]);\n var dp = new Array(m).fill(0);\n // from left to right\n dp[0] = Math.min(restrictions[0][0]-1, restrictions[0][1]);\n for(var i = 1; i<m; i++)\n {\n dp[i] = Math.min(dp[i-1] + restrictions[i][0]-restrictions[i-1][0],restrictions[i][1]);\n }\n // from right to left\n for(var i = m-2; i>=0; i--)\n {\n dp[i] = Math.min(dp[i], dp[i+1] + restrictions[i+1][0]-restrictions[i][0]);\n }\n // find max\n var max = Math.max(dp[0], dp[m-1]+ n - restrictions[m-1][0]); // 1st Restricted Building OR last Resticted Building until the end\n for(var i = 1; i<m; i++)\n {\n // between [i-1,...i] the highest is the middle part, height = max(i,i-1) + (interval - hegith_diff) / 2\n var middleHeight = Math.max(dp[i], dp[i-1]) + Math.floor((restrictions[i][0] - restrictions[i-1][0] - Math.abs(dp[i]-dp[i-1])) / 2); \n max = Math.max(max, middleHeight);\n }\n return max;\n};\n``` | 0 | 1 | [] | 0 |
maximum-building-height | JAVA n*log(n) With explanation | java-nlogn-with-explanation-by-niranjvin-6nwh | It is pretty simple. the algorithm is self explanatory\n\n1) sort the restrictions with respect to index\n2) add restriction for 1st building as 0 and last buil | niranjvin | NORMAL | 2021-04-25T04:46:52.212011+00:00 | 2021-04-25T05:56:54.139332+00:00 | 270 | false | It is pretty simple. the algorithm is self explanatory\n\n1) sort the restrictions with respect to index\n2) add restriction for 1st building as 0 and last build(if it does not exist) as (number of buildings - 1)\n3) traverse left to right and check adjacent buildings with restrictions(not literally adjacent). if H(LeftB) < H(rightB) , set H(RightB) = maximum possible which is H(LeftB) - distance between them. I dont want to change the height of left building since it would create a rippling effect.\n\n4) traverse right to left. check in a similar way (change only left building this time).\n5) max height is one of these newly calculated maximum heights OR you can keep raising 2 adjacent building WITH restrictions to meet at a higher building in the middle. this would be Max H between the two B + Math.ceil( distance between them - (difference in max height) / 2)\n\n```\nclass Solution {\n public int maxBuilding(int n, int[][] restrictions) {\n if( n == 0) return 0;\n Arrays.sort(restrictions, (a,b) -> a[0]-b[0]);\n int size = restrictions.length+1;\n if(restrictions.length == 0 || restrictions[restrictions.length-1][0] != n){\n size++;\n }\n \n long r[][] = new long[size][2];\n r[0][0] = 1;\n r[0][1] = 0;\n \n\n \n for(int i = 0;i<restrictions.length;i++){\n r[i+1][0] = restrictions[i][0];\n r[i+1][1] = restrictions[i][1];\n }\n \n if(r.length == restrictions.length+2){\n r[r.length-1][0] = n;\n r[r.length-1][1] = n-1;\n }\n \n \n for(int i = 1;i<r.length;i++){\n long[] left = r[i-1];\n long[] right = r[i];\n \n long width = right[0] - left[0];\n if(left[1] < right[1]){\n right[1] = Math.min(right[1], left[1] + width);\n }\n \n }\n \n \n long ans = 0;\n \n \n \n for(int i=r.length-2;i>=0;i--){\n long[] left = r[i];\n long[] right = r[i+1];\n long width = right[0] - left[0];\n if(left[1] > right[1]){\n left[1] = Math.min(left[1], right[1] + width);\n }\n \n long eq = Math.abs(right[1] - left[1]);\n width = width - eq - 1;\n ans = Math.max(ans, Math.max(right[1], left[1]) + (long) Math.ceil(width/(double)2));\n }\n\n for(long val[] : r){\n ans = Math.max(ans, val[1]);\n }\n \n return (int)Math.min(Integer.MAX_VALUE, ans);\n \n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
maximum-building-height | [C#] O(M LogM) solution | c-om-logm-solution-by-micromax-foqj | Idea is first sort restrictions by bulding index, then compute maximum possible height in each restriction point walking from left and from right. And then at t | micromax | NORMAL | 2021-04-25T04:38:19.416522+00:00 | 2021-04-25T04:48:56.866949+00:00 | 84 | false | Idea is first sort restrictions by bulding index, then compute maximum possible height in each restriction point walking from left and from right. And then at the end compute max possible hight between two restricted buildings.\n\nCurrent execution is ~0.8sec so its a pass but not optimal.\n\n\n```\npublic class Solution {\n public int MaxBuilding(int n, int[][] restrictions) {\n Array.Sort(restrictions, (x, y) => x[0].CompareTo(y[0]));\n // initialize restrictions list R, add borders 0 and N as well.\n var r = new List<(int Idx, int Height)>(restrictions.Length+2);\n r.Add((Idx: 1, Height: 0));\n for(var i = 0; i < restrictions.Length; i++){\n r.Add((Idx: restrictions[i][0], Height: restrictions[i][1]));\n }\n \n if (r[r.Count-1].Idx != n){\n r.Add((Idx: n, Height: 1000000001));\n }\n \n // Compute Max possible height at the point of restriction (walking from left and walking from right)\n var lH = new int[r.Count];\n var rH = new int[r.Count];\n var j = 0;\n rH[r.Count-1] = 1000000001;\n \n for(var i = 1; i < r.Count; i++){\n // walking form left\n lH[i] = r[i].Height;\n lH[i] = Math.Min(lH[i], lH[i-1] + r[i].Idx-r[i-1].Idx); \n \n // walking from right\n j = r.Count -1 - i;\n rH[j] = r[j].Height;\n rH[j] = Math.Min(rH[j], rH[j+1] + r[j+1].Idx-r[j].Idx); \n }\n\n // merge two peak arrays. Pick shortest height\n for(var i = 0; i < r.Count; i++){\n lH[i] = lH[i] > rH[i] ? rH[i] : lH[i]; \n }\n \n var maxHeight = lH[0];\n for(var i = 1; i < r.Count; i++){\n // compute max possible height between two peaks\n var k = Math.Abs(r[i].Idx - r[i-1].Idx);\n var d = Math.Abs(lH[i] - lH[i-1]);\n k -= d;\n k = k < 0 ? 0 : k;\n k = k /2;\n maxHeight = Math.Max(maxHeight, Math.Max(lH[i], lH[i-1]) + k);\n } \n \n return maxHeight;\n }\n}\n```\n\n | 0 | 0 | [] | 0 |
maximum-building-height | sorting + O(N) solution with explanation Python 3 | sorting-on-solution-with-explanation-pyt-w0ln | first comb from the left to right to make sure that the i th restriction is within range of the i-1 th restriction\nThen comb from the right to left to make sur | ljpsy | NORMAL | 2021-04-25T04:19:11.743578+00:00 | 2021-04-25T04:29:36.279206+00:00 | 103 | false | first comb from the left to right to make sure that the i th restriction is within range of the i-1 th restriction\nThen comb from the right to left to make sure that the i-1 th restriction is within range of the i th restriction\nFinally, compute the maximum height can be achieved between adjacent restrictions, using ``` ans = max(ans, lh+mid-left) ```\n\nNote, the 1st and last building height are added to smooth the boundary condition check.\n\n```\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n restrictions = sorted(restrictions)\n restrictions = [[idx,min(idx-1,h) ] for idx, h in [[1,0]] + restrictions ] # first building height is 0\n if restrictions[-1][0] != n: restrictions.append([n,n-1]) #smooth boundary condition check\n for i, (idx, h) in enumerate(restrictions[1:],1): # comb from left to right\n pidx, ph = restrictions[i-1]\n restrictions[i][1] = min(h, ph+idx-pidx)\n \n for i in reversed(range(1,len(restrictions))): # comb from right to left\n pidx, ph = restrictions[i-1]\n idx, h = restrictions[i]\n restrictions[i-1][1] = min(ph, h+idx-pidx)\n \n ans = 0\n for i, (left, lh) in enumerate(restrictions[:-1]): # compute by maths, which is greedy\n right, rh = restrictions[i+1]\n mid = (left+right+rh-lh)//2\n ans = max(ans, lh+mid-left)\n \n return ans\n \n``` | 0 | 0 | [] | 0 |
maximum-building-height | preprocess and iterative simulation | preprocess-and-iterative-simulation-by-b-nkfx | \nfunc maxBuilding(n int, restrictions [][]int) (ans int) {\n sort.Slice(restrictions, func(i, j int)bool{return restrictions[i][0] < restrictions[j][0]})\n | bcb98801xx | NORMAL | 2021-04-25T04:15:00.613894+00:00 | 2021-04-25T04:15:00.613921+00:00 | 66 | false | ```\nfunc maxBuilding(n int, restrictions [][]int) (ans int) {\n sort.Slice(restrictions, func(i, j int)bool{return restrictions[i][0] < restrictions[j][0]})\n \n for i := len(restrictions) - 1; i > 0; i-- {\n\t\tif restrictions[i][1] > restrictions[i-1][1] {\n\t\t\trestrictions[i][1] = min(restrictions[i][1], restrictions[i-1][1]+restrictions[i][0]-restrictions[i-1][0])\n\t\t} else {\n\t\t\trestrictions[i-1][1] = min(restrictions[i-1][1], restrictions[i][1]+restrictions[i][0]-restrictions[i-1][0])\n\t\t}\n\t}\n \n prevh := 0\n previd := 1\n \n for _, restrict := range restrictions {\n if tmp := restrict[0]-previd; tmp+prevh <= restrict[1]{\n prevh += tmp\n ans = max(ans, prevh)\n }else{\n if tmp := (restrict[0]-previd-abs(restrict[1]-prevh))>>1; tmp > 0 {\n ans = max(ans, max(prevh, restrict[1])+tmp)\n }else{\n ans = max(ans, restrict[1])\n } \n prevh = restrict[1]\n }\n \n previd = restrict[0]\n }\n \n ans = max(ans, prevh+n-previd)\n \n return ans\n}\n\nfunc abs(a int)int{\n if a < 0 {return -a}\n \n return a\n}\n\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\n\treturn b\n}\n\nfunc max(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\n\treturn b\n}\n``` | 0 | 0 | [] | 0 |
maximum-building-height | [Python] greedy solution with brief explanation comments | python-greedy-solution-with-brief-explan-0r5s | The bottle neck is sort.\nAfter sorting you can see from 1 to N and then go back to find maximum height.\n\nINF = float(\'inf\')\nclass Solution:\n def maxBu | tada_24 | NORMAL | 2021-04-25T04:09:57.127752+00:00 | 2021-04-25T04:09:57.127788+00:00 | 105 | false | The bottle neck is sort.\nAfter sorting you can see from 1 to N and then go back to find maximum height.\n```\nINF = float(\'inf\')\nclass Solution:\n def maxBuilding(self, N: int, R: List[List[int]]) -> int:\n R = [[id-1,h] for id, h in R]\n R.append([0, 0])\n R.sort()\n if R[-1][0] != N-1: # do not have N building restriction\n R.append([N-1, INF])\n \n M = len(R)\n id2idx = {}\n idx2id = {}\n \n for idx, (id, _) in enumerate(R):\n id2idx[id] = idx\n idx2id[idx] = id \n \n # greedy from 1 to N building\n H = [INF for _ in range(M)]; H[0] = 0 \n for idx in range(1, M):\n prev_h = H[idx-1]; prev_id = idx2id[idx-1]\n cur_max_h = R[idx][1]; cur_id = idx2id[idx]\n if prev_h - (cur_id-prev_id) > cur_max_h:\n H[idx] = cur_max_h\n else:\n H[idx] = min(prev_h + (cur_id-prev_id), cur_max_h)\n \n \n # greedy from N to 1 building\n # adjust height and find max height\n ret = H[M-1]\n for idx in range(M-2, -1, -1):\n prev_h = H[idx+1]; prev_id = idx2id[idx+1]\n cur_h = H[idx]; cur_id = idx2id[idx]\n \n if cur_h > prev_h + (prev_id-cur_id): # need to adjust\n H[idx] = prev_h + (prev_id-cur_id)\n ret = max(ret, H[idx])\n else:\n ret = max(ret, cur_h)\n # cur_h + x - y = prev_h & x+y = prev_id - cur_id\n if cur_h >= prev_h: # max is cur_h + x\n su = (prev_id-cur_id) # x+y\n diff = prev_h-cur_h # x-y\n x2 = su+diff # 2*x\n x = x2//2\n ret = max(ret, cur_h+max(0, x))\n else: # max is prev_h + y\n su = (prev_id-cur_id) # x+y\n diff = cur_h-prev_h # y-x\n y2 = su+diff # 2*y\n y = y2//2\n ret = max(ret, prev_h+max(0, y))\n \n return ret\n``` | 0 | 0 | [] | 0 |
longest-palindrome | Simple HashSet solution Java | simple-hashset-solution-java-by-charlieb-8z2c | \npublic int longestPalindrome(String s) {\n if(s==null || s.length()==0) return 0;\n HashSet<Character> hs = new HashSet<Character>();\n i | charliebob64 | NORMAL | 2016-10-02T06:18:20.299000+00:00 | 2018-10-12T03:34:24.980379+00:00 | 72,140 | false | ```\npublic int longestPalindrome(String s) {\n if(s==null || s.length()==0) return 0;\n HashSet<Character> hs = new HashSet<Character>();\n int count = 0;\n for(int i=0; i<s.length(); i++){\n if(hs.contains(s.charAt(i))){\n hs.remove(s.charAt(i));\n count++;\n }else{\n hs.add(s.charAt(i));\n }\n }\n if(!hs.isEmpty()) return count*2+1;\n return count*2;\n}\n``` | 421 | 7 | [] | 61 |
longest-palindrome | C++ - Easiest Beginner Friendly Sol || O(n) time and O(128) = O(1) space | c-easiest-beginner-friendly-sol-on-time-9m3hu | Intuition of this Problem:\n Describe your first thoughts on how to solve this problem. \nNOTE - PLEASE READ APPROACH FIRST THEN SEE THE CODE. YOU WILL DEFINITE | singhabhinash | NORMAL | 2023-02-07T14:27:55.936990+00:00 | 2023-02-07T14:27:55.937033+00:00 | 40,608 | false | # Intuition of this Problem:\n<!-- Describe your first thoughts on how to solve this problem. -->\n**NOTE - PLEASE READ APPROACH FIRST THEN SEE THE CODE. YOU WILL DEFINITELY UNDERSTAND THE CODE LINE BY LINE AFTER SEEING THE APPROACH.**\n\n# Approach for this Problem:\n1. Initialize two variables, oddCount to store the number of characters with an odd count of occurrences and an unordered map ump to store the count of each character in the string.\n2. Iterate through the string and for each character ch, increment the count of that character in the unordered map.\n3. If the count of the current character ch is odd, increment oddCount. If the count is even, decrement oddCount.\n4. If oddCount is greater than 1, return s.length() - oddCount + 1, which is the maximum length of a palindrome that can be formed by using all but one character with an odd count of occurrences.\n5. If oddCount is not greater than 1, return s.length(), which is the length of the original string, as all characters can be used to form a palindrome.\n<!-- Describe your approach to solving the problem. -->\n\n# Humble Request:\n- If my solution is helpful to you then please **UPVOTE** my solution, your **UPVOTE** motivates me to post such kind of solution.\n- Please let me know in comments if there is need to do any improvement in my approach, code....anything.\n- **Let\'s connect on** https://www.linkedin.com/in/abhinash-singh-1b851b188\n\n\n\n# Code:\n```C++ []\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n int oddCount = 0;\n unordered_map<char, int> ump;\n for(char ch : s) {\n ump[ch]++;\n if (ump[ch] % 2 == 1)\n oddCount++;\n else \n oddCount--;\n }\n if (oddCount > 1)\n return s.length() - oddCount + 1;\n return s.length();\n }\n};\n```\n```Java []\nclass Solution {\n public int longestPalindrome(String s) {\n int oddCount = 0;\n Map<Character, Integer> map = new HashMap<>();\n for (char ch : s.toCharArray()) {\n map.put(ch, map.getOrDefault(ch, 0) + 1);\n if (map.get(ch) % 2 == 1)\n oddCount++;\n else\n oddCount--;\n }\n if (oddCount > 1)\n return s.length() - oddCount + 1;\n return s.length();\n }\n}\n\n```\n```Python []\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n odd_count = 0\n d = {}\n for ch in s:\n if ch in d:\n d[ch] += 1\n else:\n d[ch] = 1\n if d[ch] % 2 == 1:\n odd_count += 1\n else:\n odd_count -= 1\n if odd_count > 1:\n return len(s) - odd_count + 1\n return len(s)\n\n```\n\n# Time Complexity and Space Complexity:\n- Time complexity: **O(n)**, where n is the length of the string s. This is because we are iterating through the string only once.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(m)**, where m is the number of unique characters in the string. This is because we are using an unordered map to store the count of each character.\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> | 367 | 0 | ['Hash Table', 'C++', 'Java', 'Python3'] | 13 |
longest-palindrome | What are the odds? (Python & C++) | what-are-the-odds-python-c-by-stefanpoch-jo5m | I count how many letters appear an odd number of times. Because we can use all letters, except for each odd-count letter we must leave one, except one of them w | stefanpochmann | NORMAL | 2016-10-02T13:44:40.212000+00:00 | 2018-10-10T08:52:45.698003+00:00 | 48,310 | false | I count how many letters appear an odd number of times. Because we can use **all** letters, except for each odd-count letter we must leave one, except one of them we can use.\n\nPython:\n\n def longestPalindrome(self, s):\n odds = sum(v & 1 for v in collections.Counter(s).values())\n return len(s) - odds + bool(odds)\n\nC++:\n\n int longestPalindrome(string s) {\n int odds = 0;\n for (char c='A'; c<='z'; c++)\n odds += count(s.begin(), s.end(), c) & 1;\n return s.size() - odds + (odds > 0);\n }\n\nSimilar solutions (I actually like the `use` solutions better than the above, but I'm just so fond of my topic title :-)\n\n def longestPalindrome(self, s):\n use = sum(v & ~1 for v in collections.Counter(s).values())\n return use + (use < len(s))\n\n def longestPalindrome(self, s):\n counts = collections.Counter(s).values()\n return sum(v & ~1 for v in counts) + any(v & 1 for v in counts)\n\n int longestPalindrome(string s) {\n int use = 0;\n for (char c='A'; c<='z'; c++)\n use += count(s.begin(), s.end(), c) & ~1;\n return use + (use < s.size());\n }\n\n int longestPalindrome(string s) {\n vector<int> count(256);\n for (char c : s)\n ++count[c];\n int odds = 0;\n for (int c : count)\n odds += c & 1;\n return s.size() - odds + (odds > 0);\n }\n\n int longestPalindrome(string s) {\n vector<int> count(256);\n int odds = 0;\n for (char c : s)\n odds += ++count[c] & 1 ? 1 : -1;\n return s.size() - odds + (odds > 0);\n } | 323 | 7 | [] | 31 |
longest-palindrome | 💯Faster✅💯Less Mem✅🧠Detailed Approach🎯Set Approach🔥Python🐍Java☕C++😎 | fasterless-memdetailed-approachset-appro-pbyp | \uD83D\uDE80 Hi, I\'m Mohammed Raziullah Ansari, and I\'m excited to share solution to this question with detailed explanation:\n\n# \uD83C\uDFAFProblem Explain | Mohammed_Raziullah_Ansari | NORMAL | 2024-06-04T00:07:07.489474+00:00 | 2024-06-04T01:17:43.199934+00:00 | 36,114 | false | # \uD83D\uDE80 Hi, I\'m [Mohammed Raziullah Ansari](https://leetcode.com/Mohammed_Raziullah_Ansari/), and I\'m excited to share solution to this question with detailed explanation:\n\n# \uD83C\uDFAFProblem Explaination: \nThe problem is to find the length of the longest palindrome that can be constructed using the characters from a given string. \n\nA palindrome is a sequence of characters that reads the same backward as forward. For example, "racecar" and "level" are palindromes.\n\n## \uD83D\uDCE5Input\n- A single string \\( s \\) containing only lowercase and/or uppercase English letters.\n\n## \uD83D\uDCE4Output\n- An integer representing the length of the longest possible palindrome that can be formed with the characters of the given string.\n\n# \uD83E\uDDE0Thinking Behind the Solution:\n\nThe idea behind the solution is to use a set to help us count pairs of characters, and then determine if we can have a single middle character in our palindrome. Here\'s the thought process:\n\n1. **Initialize a Set:**\n - We start with an empty set. This set will help us keep track of characters that appear an odd number of times.\n\n2. **Iterate Over the Characters:**\n - For each character in the string, we check if it is already in the set.\n\n3. **Check for Pairs:**\n - If the character is in the set, it means we have found a pair (one character we saw earlier plus this one).\n - We remove this character from the set because we have used up the pair.\n - We increase our palindrome length by 2 because a pair of characters can be placed symmetrically in the palindrome (one on the left side and one on the right side).\n\n4. **Track Odd Characters:**\n - If the character is not in the set, we add it to the set. This means we have seen this character once, and it might be part of a pair if we see it again later.\n\n5. **Check for Middle Character:**\n - After processing all characters, if there are any characters left in the set, it means these characters appear an odd number of times.\n - We can use one of these characters as the middle character of the palindrome (since a palindrome can have one character in the center without a pair).\n\n6. **Calculate the Length:**\n - The total length of the palindrome will be the number of pairs we found (each pair contributes 2 to the length).\n - If we have any characters left in the set, we add 1 to the length for the single middle character.\n\n# Let\'s walkthrough\uD83D\uDEB6\uD83C\uDFFB\u200D\u2642\uFE0F the implementation process with an example for better understanding\uD83C\uDFAF:\n\nLet\'s take the string "abccccdd" as an example:\n\n1. **Initial State:**\n - Set: {}\n\n2. **Process Each Character:**\n - \'a\' is not in the set. Add \'a\'. Set: {\'a\'}\n - \'b\' is not in the set. Add \'b\'. Set: {\'a\', \'b\'}\n - \'c\' is not in the set. Add \'c\'. Set: {\'a\', \'b\', \'c\'}\n - Another \'c\'. It\'s already in the set. Remove \'c\'. Increase length by 2. Length: 2. Set: {\'a\', \'b\'}\n - Another \'c\'. Add \'c\'. Set: {\'a\', \'b\', \'c\'}\n - Another \'c\'. It\'s already in the set. Remove \'c\'. Increase length by 2. Length: 4. Set: {\'a\', \'b\'}\n - \'d\' is not in the set. Add \'d\'. Set: {\'a\', \'b\', \'d\'}\n - Another \'d\'. It\'s already in the set. Remove \'d\'. Increase length by 2. Length: 6. Set: {\'a\', \'b\'}\n\n3. **Final Check:**\n - The set still has {\'a\', \'b\'}, meaning we have characters that appeared an odd number of times.\n - We can use one of these characters as the center of the palindrome. Add 1 to the length. Final Length: 7.\n\nSo, the longest palindrome we can build with "abccccdd" has a length of 7.\n# \u2705Approach:\n1. **Initialize Variables:**\n - Create an empty set to keep track of characters that appear an odd number of times.\n - Initialize a variable `length` to keep track of the length of the palindrome.\n\n2. **Iterate Over the Characters of the String:**\n - For each character in the string, check if it is in the set.\n - If it is in the set, remove it from the set and increase the `length` by 2.\n - If it is not in the set, add it to the set.\n\n3. **Check for Odd Characters:**\n - After processing all characters, check if there are any characters left in the set.\n - If the set is not empty, it means there are characters that appear an odd number of times. Add 1 to the `length` for the center character of the palindrome.\n\n4. **Return the Length:**\n - Return the calculated `length` of the longest palindrome.\n\n# Code\uD83D\uDC69\uD83C\uDFFB\u200D\uD83D\uDCBB:\n```Python []\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n # Initialize a set to keep track of characters with odd frequencies\n char_set = set()\n # Initialize the length of the longest palindrome\n length = 0\n \n # Iterate over each character in the string\n for char in s:\n # If the character is already in the set, remove it and increase the length by 2\n if char in char_set:\n char_set.remove(char)\n length += 2\n # If the character is not in the set, add it to the set\n else:\n char_set.add(char)\n \n # If there are any characters left in the set, add 1 to the length for the middle character\n if char_set:\n length += 1\n \n # Return the total length of the longest palindrome\n return length\n```\n```Java []\npublic class Solution {\n public int longestPalindrome(String s) {\n // Initialize a set to keep track of characters with odd frequencies\n HashSet<Character> charSet = new HashSet<>();\n // Initialize the length of the longest palindrome\n int length = 0;\n \n // Iterate over each character in the string\n for (char c : s.toCharArray()) {\n // If the character is already in the set, remove it and increase the length by 2\n if (charSet.contains(c)) {\n charSet.remove(c);\n length += 2;\n } else {\n // If the character is not in the set, add it to the set\n charSet.add(c);\n }\n }\n \n // If there are any characters left in the set, add 1 to the length for the middle character\n if (!charSet.isEmpty()) {\n length += 1;\n }\n \n // Return the total length of the longest palindrome\n return length;\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n int longestPalindrome(const std::string& s) {\n // Initialize a set to keep track of characters with odd frequencies\n std::unordered_set<char> charSet;\n // Initialize the length of the longest palindrome\n int length = 0;\n \n // Iterate over each character in the string\n for (char c : s) {\n // If the character is already in the set, remove it and increase the length by 2\n if (charSet.find(c) != charSet.end()) {\n charSet.erase(c);\n length += 2;\n } else {\n // If the character is not in the set, add it to the set\n charSet.insert(c);\n }\n }\n \n // If there are any characters left in the set, add 1 to the length for the middle character\n if (!charSet.empty()) {\n length += 1;\n }\n \n // Return the total length of the longest palindrome\n return length;\n }\n};\n\n\n```\n\n# \uD83D\uDCA1 I invite you to check out [my profile](https://leetcode.com/Mohammed_Raziullah_Ansari/) for detailed explanations and code for each method. Happy coding and learning! \uD83D\uDCDA | 157 | 6 | ['String', 'C++', 'Java', 'Python3'] | 26 |
longest-palindrome | python simple set solution | python-simple-set-solution-by-howezz-c863 | \nclass Solution(object):\n def longestPalindrome(self, s):\n """\n :type s: str\n :rtype: int\n """\n hash = set()\n | howezz | NORMAL | 2017-06-25T19:41:54.244000+00:00 | 2018-08-19T19:11:06.949357+00:00 | 16,949 | false | ```\nclass Solution(object):\n def longestPalindrome(self, s):\n """\n :type s: str\n :rtype: int\n """\n hash = set()\n for c in s:\n if c not in hash:\n hash.add(c)\n else:\n hash.remove(c)\n # len(hash) is the number of the odd letters\n return len(s) - len(hash) + 1 if len(hash) > 0 else len(s)\n``` | 145 | 1 | [] | 17 |
longest-palindrome | Easy || 100% || Fully Explained || Java || Clean Solution || Using HashSet || O(n) | easy-100-fully-explained-java-clean-solu-zpz4 | Java Solution:\n\n// Runtime: 4 ms, faster than 79.44% of Java online submissions for Longest Palindrome.\n// Time Complexity : O(n)\nclass Solution {\n publ | PratikSen07 | NORMAL | 2022-08-27T14:38:33.871518+00:00 | 2022-08-28T06:53:23.930487+00:00 | 15,174 | false | # **Java Solution:**\n```\n// Runtime: 4 ms, faster than 79.44% of Java online submissions for Longest Palindrome.\n// Time Complexity : O(n)\nclass Solution {\n public int longestPalindrome(String s) {\n int length = 0;\n // Create a HashSet...\n HashSet<Character> hset = new HashSet<Character>();\n // Traverse every element through the loop...\n for (int idx = 0; idx < s.length(); idx++) {\n // Convert string to character array...\n char character = s.charAt(idx);\n // If hset contains character already, emove that character & adding 2 to length...\n // It means we get pair of character which is used in palindrome...\n if (hset.contains(character)) {\n length += 2;\n hset.remove(character);\n }\n // Otherwise, add the character to the hashset...\n else {\n hset.add(character);\n }\n }\n // If the size of the set is greater than zero, move length forward...\n if (hset.size() > 0) {\n length ++;\n }\n return length; // Return the length of the longest palindrome...\n }\n}\n```\n**I am working hard for you guys...\nPlease upvote if you found any help with this code...** | 132 | 1 | ['Hash Table', 'String', 'Java'] | 7 |
longest-palindrome | Python 3 solution using Set() | python-3-solution-using-set-by-michaelka-j49e | Idea:\nStart adding letters to a set. If a given letter not in the set, add it. If the given letter is already in the set, remove it from the set. \nIf the set | michaelkareev | NORMAL | 2020-08-27T00:47:56.802376+00:00 | 2020-08-27T00:47:56.802428+00:00 | 13,925 | false | **Idea**:\nStart adding letters to a set. If a given letter not in the set, add it. If the given letter is already in the set, remove it from the set. \nIf the set isn\'t empty, you need to return length of the string minus length of the set plus 1.\nOtherwise, you return the length of the string (example \'bb.\' Your set is empty, you just return 2).\n\nEssentially, your set contains non-paired letters. It\'s one of those bad questions where you need to go over all possible cases and somehow fit them into the solution. \n\n```\ndef longestPalindrome_set(s):\n ss = set()\n for letter in s:\n if letter not in ss:\n ss.add(letter)\n else:\n ss.remove(letter)\n if len(ss) != 0:\n return len(s) - len(ss) + 1\n else:\n return len(s)\n``` | 129 | 0 | ['Ordered Set', 'Python', 'Python3'] | 10 |
longest-palindrome | JavaScript solution with a single for loop | javascript-solution-with-a-single-for-lo-ex8s | We don\'t have to make an additional loop through keys.\n\n\nvar longestPalindrome = function(s) {\n let ans = 0;\n let keys = {};\n \n for (let char of s) | gorkiy | NORMAL | 2019-09-26T15:50:18.382572+00:00 | 2019-09-26T15:50:18.382625+00:00 | 8,390 | false | We don\'t have to make an additional loop through keys.\n\n```\nvar longestPalindrome = function(s) {\n let ans = 0;\n let keys = {};\n \n for (let char of s) {\n keys[char] = (keys[char] || 0) + 1;\n if (keys[char] % 2 == 0) ans += 2;\n }\n return s.length > ans ? ans + 1 : ans;\n};\n``` | 105 | 1 | ['JavaScript'] | 11 |
longest-palindrome | [C++/Python/Java] It is only easy when you think really hard to spot the built-in nature | cpythonjava-it-is-only-easy-when-you-thi-0rga | idea\uFF1A count the frequency of each char, the chars appears even times can all be kept, however, the chars appears odd times must remove one char, then the r | codedayday | NORMAL | 2020-08-14T15:35:18.223474+00:00 | 2020-12-25T22:40:27.390121+00:00 | 19,658 | false | idea\uFF1A count the frequency of each char, the chars appears even times can all be kept, however, the chars appears odd times must remove one char, then the rest instances of that char can be collected for composition. Finally, the middle char can be from OddGroup\nExample: "abccccdd",\nstep 1: count freq of char before clearning: \na:1\nb:1\nc:4\nd:2\n\nstep 2: perform clearning and prepare for palindrom composition:\na:0\nb:0\nc:4\nd:2\nanswer = s.size() - 1 - 1\nStep 3: make correction, if necessary (i.e., when at least one char shows odd times)\nif OddGroup > 0: answer +=1\n\nRef: https://leetcode.com/problems/longest-palindrome/discuss/89587/What-are-the-odds-(Python-and-C%2B%2B)\n```\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n int freq[128]={};\n for(auto c:s) ++freq[c];\n int OddGroup = 0; //count of uniq char which shows up odd times, help me if you have better naming \n for(auto i:freq) OddGroup += i & 1;\n return s.size() - OddGroup + (OddGroup > 0); \n }\n}; \n```\n\nPython:\n```\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n freq = [0]*128;\n for c in s:freq[ord(c)]+=1\n OddGroup = 0\n for i in freq: OddGroup += i & 1\n return len(s) - OddGroup + (OddGroup > 0) \n```\n\nJava:\n```\nclass Solution {\n public int longestPalindrome(String s) {\n int[] freq = new int[128]; \n for(char c:s.toCharArray()) ++freq[c];\n int OddGroup = 0;\n for(int i:freq) OddGroup += i & 1;\n return s.length() - OddGroup + (OddGroup > 0 ? 1:0); // Waiting for a better way to convert boolean into int \n }\n}\n``` | 100 | 1 | ['C', 'Python', 'Java'] | 11 |
longest-palindrome | ✅✅|| Easiest Solution || Approach || C++ || JAVA || PYTHON || JAVASCRIPT || Beginner Friendly🔥🔥🔥 | easiest-solution-approach-c-java-python-zj2e6 | Intuition\n Describe your first thoughts on how to solve this problem. \nTo form the longest palindrome from the given string, we need to understand the propert | _HeLL0____ | NORMAL | 2024-06-04T00:13:17.277241+00:00 | 2024-06-04T00:13:17.277269+00:00 | 12,938 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo form the longest palindrome from the given string, we need to understand the properties of a palindrome:\n\nA palindrome reads the same forwards and backwards.\nFor this to happen, each character must appear an even number of times so they can be mirrored around the center.\nAt most one character can appear an odd number of times (it will be placed in the center).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCount the frequency of each character in the string.\nInitialize a variable to keep track of the length of the longest palindrome.\nIterate over the frequency counts:\nIf a character count is even, it can be fully used in the palindrome.\nIf a character count is odd, use the largest even part of it (e.g., if the count is 5, use 4 of them), and keep track of the fact that you have an odd character available.\nIf there is at least one odd character, one of these can be placed in the center of the palindrome.\nThe result will be the sum of the lengths computed from the above steps.\n\n# Explaination\nCounting Frequencies and Odd Counts:\n\nAs you iterate through each character in the string, you count the occurrences of each character using an unordered map.\nFor each character, you update the oddCount based on whether the current count of that character is odd or even.\nIf a character\'s count becomes odd, you increment oddCount.\nIf a character\'s count becomes even, you decrement oddCount.\n\n\nDetermining the Longest Palindrome Length:\n\nIf there is more than one character with an odd count, the longest palindrome can use all but one of those odd-count characters (which will be placed in the center). Thus, s.length() - oddCount + 1 gives the correct length.\nIf there is at most one character with an odd count, the entire string can be rearranged into a palindrome.\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n int oddFrequencyCount = 0;\n unordered_map<char, int> charFrequency;\n for (char ch : s) {\n charFrequency[ch]++;\n if (charFrequency[ch] % 2 == 1)\n oddFrequencyCount++;\n else\n oddFrequencyCount--;\n }\n if (oddFrequencyCount > 1)\n return s.length() - oddFrequencyCount + 1;\n return s.length();\n }\n};\n```\n```Java []\npublic class Solution {\n public int longestPalindrome(String s) {\n HashMap<Character, Integer> charFrequency = new HashMap<>();\n int oddFrequencyCount = 0;\n for (char ch : s.toCharArray()) {\n charFrequency.put(ch, charFrequency.getOrDefault(ch, 0) + 1);\n if (charFrequency.get(ch) % 2 == 1)\n oddFrequencyCount++;\n else\n oddFrequencyCount--;\n }\n if (oddFrequencyCount > 1)\n return s.length() - oddFrequencyCount + 1;\n return s.length();\n }\n}\n```\n```python []\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n charFrequency = Counter(s)\n oddFrequencyCount = 0\n for frequency in charFrequency.values():\n if frequency % 2 == 1:\n oddFrequencyCount += 1\n if oddFrequencyCount > 1:\n return len(s) - oddFrequencyCount + 1\n return len(s)\n```\n```Javascript []\nclass Solution {\n longestPalindrome(s) {\n let charFrequency = {};\n let oddFrequencyCount = 0;\n for (let char of s) {\n charFrequency[char] = (charFrequency[char] || 0) + 1;\n if (charFrequency[char] % 2 === 1)\n oddFrequencyCount++;\n else\n oddFrequencyCount--;\n }\n if (oddFrequencyCount > 1)\n return s.length - oddFrequencyCount + 1;\n return s.length;\n }\n}\n```\n\n\n\n | 61 | 3 | ['String', 'Python', 'C++', 'Java', 'JavaScript'] | 21 |
longest-palindrome | [Python] 2 lines with counter + Oneliner, explained | python-2-lines-with-counter-oneliner-exp-3ccv | Note, that it every palindrome we need to use every letter even number of times, maybe except one letter in the middle. Note also, that this condition is also s | dbabichev | NORMAL | 2020-08-14T08:21:17.270140+00:00 | 2020-08-14T09:51:58.599274+00:00 | 4,522 | false | Note, that it every palindrome we need to use every letter `even` number of times, maybe except one letter in the middle. Note also, that this condition is also sufficient: if we have frequencies for each letter which are even and one frequence is odd, we can always create palindrome. For example let us have `aaaaaa`, `c`, `bbbb`, then we create `aaabbcbbaaa`.\n\nSo, all we need to do is to count frequencies of each letter and take as much letters as possible. There are two possible cases:\n1. If we have only `zero` or `one` letters with odd frequencies, then we can use all the letters.\n2. If we have `k>1` letters with odd frequencies, we need to remove exactly `k-1` letter to build palindrome.\n\n**Complexity**: space complexity is `O(k)`, where `k` is size of used alphabet. Time complexity is `O(n)`, where `n` is length of our string: we process it once to get counter, then we find reminders of frequencies modulo `2` in `O(k)`.\n\n\n```\nclass Solution:\n def longestPalindrome(self, s):\n odds = sum([freq % 2 for _,freq in Counter(s).items()])\n return len(s) if odds <=1 else len(s) - odds + 1 \n```\n\n### Oneliner\nThe same logic can be written as oneliner\n```return len(s) if (o:=sum([f%2 for _,f in Counter(s).items()])) <=1 else len(s)-o+1```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!** | 59 | 1 | [] | 5 |
longest-palindrome | ~~Highly~~ || Extreme Visualise Solution || 2 Approaches 😱😱 | highly-extreme-visualise-solution-2-appr-7w8b | We will have a string, using that characters from the string. We have to tell that. How much longest length palindrome is possible. \nAnd we have to return that | hi-malik | NORMAL | 2024-06-04T01:06:10.348951+00:00 | 2024-06-04T01:34:54.508212+00:00 | 7,240 | false | We will have a string, using that characters from the string. We have to tell that. How much longest length palindrome is possible. \nAnd we have to return that longest length.\n\nWhat is **Palindrome**?\n> For example we have given a character, `a` if you read it from left to right or right to left. It going to meant the same thing!\n\n\n\n> What if we have **`ab`**, is it a palindromic string?\n\n\n* Because **left to right**, we will read it will be **ab**\n* But from **right to left**, we will read it will be **ba**\n* Hence, it\'s not\n\n> What if we have **`ab`**, is it a palindromic string?\n\n\n* Because **left to right**, we will read it will be **aba**\n* But from **right to left**, we will read it will be **aba**\n* Hence, it\'s is palindromic string\n\n**Approach - 1**\n\nSo, we don\'t have to check whether it is palindrome or not! We have to return that, using that string character, how long palindrome can we make!\nLet\'s take one example,\n```\nInput: s = "abccccdd"\nOutput: 7\n```\nWhat will be the longest palindrome, can we make using this string **s**. We can use it\'s character in any order. And we have to return the longest length. We don\'t have to make it, we just have to return the length!\n\nLet;s have few palindrome first,\n```\naabb\nabba\naccca\naaabaaa\n```\nNow, if you carefully notice that. These are only making palindrome, as if the frequency of a character is in **even number**!\n\n\nBut, this isn\'t true, because if you look at other examples you will see that, the frequency of other characters in other strings are **odd too**\n\n\nSo, what this thing conclude! Can both **even** and **odd** frequency makes a palindrome, ahhhh NO! \nLet\'s understand with one more example!\n\n\nNow in this above, example you can see that\n* `a` has 4 characters, `b` has 1 character and `c` has 3 characters\n* So, the only palindrome can be possible is, on the outer side we got even characters and in the middle or in the inner we have only **1 odd** character present. It\'s frequency doesn\'t matter, but to be a palindrome. It has to be 1 only!\n* See what I\'m saying, This is one possible palindrome\n\nAnd this is another one possible palindrome\n\n\nNow, from this what we can conclude is :\n* Either give us all **even** frequency characters\n* Or, give us **even** + **odd (frequency character has to be 1 only)**\n\nNow let\'s try to solve this problem, using the given example!\n* First, we going to create it\'s frequency map!\n\n\nNow, from this **frequency map**, how many **even** characters and **one odd** character we can take!\n* `c` is **4**\n* `d` is **2**\n* Now from `a`**/**`b` we can choose anyone as there frequency are same!\n* And return the sum of their frequency i.e. **`4 + 2 + 1 => 7`**\n\n\n **Let\'s understand with one more example**\n ```\n Input: s = "aabbbbbcccdd"\nOutput: 11\n ```\n Now let\'s try to solve this problem, using the given example!\n* First, we going to create it\'s frequency map!\n* `c` is **3**\n* `d` is **2**\n* `a` is **2**\n* `b` is **5**\n* And return the, maximum possible length of their frequency i.e. **`2 + 2 + 5 => 9`**\n* But this is wrong, it can\'t be possible\n\n\nWhy so, it\'s not possible! Because it doesn\'t mean if we have to take `c` character, we have to take it\'s all occurence. We can take only few as well.\nEven, characters we have to take at all cost. But, let\'s say we first take `b` all occuerence, but about the `c` has 3 occuerence, but we have already consider one odd previously i.e. `b`, but let\'s do one thing! Let\'s reduce down the `c` frequency by 1 to **2**. Now `c` is even, and we can have `c` too,. Let\'s look at it\'s diagram\n\n\nThe biggest possible palindrome, we can have is of length **11**\n\nSo, now let\'s code it UP!\n\n**C++**\n```\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n unordered_map<char, int> hm;\n for (int i = 0; i < s.length(); i++) {\n char c = s[i];\n if (hm.find(c) != hm.end()) {\n hm[c]++;\n } else {\n hm[c] = 1;\n }\n }\n\n int ans = 0;\n bool isFirstOdd = false;\n\n for (auto& pair : hm) {\n if (pair.second % 2 == 0) {\n ans += pair.second;\n } else {\n ans += pair.second;\n if (!isFirstOdd) {\n isFirstOdd = true;\n } else {\n ans -= 1;\n }\n }\n }\n\n return ans;\n }\n};\n```\n**JAVA**\n```\nclass Solution {\n public int longestPalindrome(String s) {\n HashMap<Character, Integer> hm = new HashMap<>();\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if (hm.containsKey(c)) {\n hm.put(c, hm.get(c) + 1);\n } else {\n hm.put(c, 1);\n }\n }\n\n int ans = 0;\n boolean isFirstOdd = false;\n\n for (Character key : hm.keySet()) {\n if (hm.get(key) % 2 == 0) {\n ans += hm.get(key);\n } else {\n ans += hm.get(key);\n if (!isFirstOdd) {\n isFirstOdd = true;\n } else {\n ans -= 1;\n }\n }\n }\n\n return ans;\n }\n}\n```\n**PYTHON**\n```\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n hm = {}\n for c in s:\n if c in hm:\n hm[c] += 1\n else:\n hm[c] = 1\n\n ans = 0\n isFirstOdd = False\n\n for key in hm:\n if hm[key] % 2 == 0:\n ans += hm[key]\n else:\n ans += hm[key]\n if not isFirstOdd:\n isFirstOdd = True\n else:\n ans -= 1\n\n return ans\n```\n\n___\nComplexity Analysis\n___\n* **Time Complexity :-** BigO(N)\n* **Space Complexity :-** BigO(K)\n\n___\n___\n\n**Approach - 2**\n\nSo, can we solve this problem without using **HASHMAP??**\n\nYes, we can do that.\n\nIn the problem, we have given that the all possible characters can be from\n* **a -> z**\n* **A -> Z**\n\n> Always, remember the ASCII value of **A** is 65! and if we add from here **26**, we will get the ASCII value of all the characters till **Z**\n> > But, if we add **32** to **65**, we will get **97**, from here all the lower case characters will start from **a**\n\nSo, instead of saving there frequency in **HashMap**, let\'s save it in array!\n* Let\'s create 2 array\n* Array one will be of **lowercase** of size **26**\n* Array one will be of **uppercase** of size **26**\n\n\nLet\'s have one example\n```\ns = "aaBBaa"\n```\n* So, we get `a` we will subtract it from **97** and if the diff is greater than or equals to **0**, we will update it\'s frequency\n* to **1**\n\n* Again, we get `a` we will subtract it from **97** and if the diff is greater than or equals to **0**, we will update it\'s frequency\n* by **1**\n\n* Now, we get `B` we will subtract it from **97** and if the diff is lesser than **0**, we will get to know that it is a **uppercase** character.\n* So, we will subtract `\'B\' - 65`, which will be `66 - 65 => 1`\n* We will update its frequency to 1 in the **uppercase** array\n\n\nDoing this, we have optimise it a little, more! Now let\'s look at it\'s code\n\nLet\'s code it UP!\n\n**C++**\n```\nclass Solution {\npublic:\n int longestPalindrome(std::string s) {\n std::vector<int> lowerCase(26, 0);\n std::vector<int> upperCase(26, 0);\n\n for(int i = 0; i < s.length(); i++) {\n char c = s[i];\n if(c - \'a\' >= 0)\n lowerCase[c - \'a\']++;\n else\n upperCase[c - \'A\']++;\n }\n\n int ans = 0;\n bool isFirstOdd = false;\n\n for(int i = 0; i < 26; i++) {\n if(lowerCase[i] % 2 == 0) {\n ans += lowerCase[i];\n } else {\n if(!isFirstOdd) {\n ans += lowerCase[i];\n isFirstOdd = true;\n } else {\n ans += lowerCase[i] - 1;\n }\n }\n }\n\n for(int i = 0; i < 26; i++) {\n if(upperCase[i] % 2 == 0) {\n ans += upperCase[i];\n } else {\n if(!isFirstOdd) {\n ans += upperCase[i];\n isFirstOdd = true;\n } else {\n ans += upperCase[i] - 1;\n }\n }\n }\n return ans;\n }\n};\n```\n**JAVA**\n```\nclass Solution {\n public int longestPalindrome(String s) {\n int lowerCase[] = new int[26];\n int upperCase[] = new int[26];\n \n for(int i =0; i <s.length(); i++){\n char c = s.charAt(i);\n if(c-97 >=0){\n lowerCase[c-97]++;\n }else{\n upperCase[c-65]++;\n }\n \n } \n \n int ans = 0;\n boolean isFirstOdd = false; \n for(int i = 0; i <26; i++){\n if(lowerCase[i]%2 ==0){\n ans += lowerCase[i];\n }else{\n if(isFirstOdd == false){\n ans += lowerCase[i]; \n isFirstOdd = true;\n }\n else\n ans += lowerCase[i]-1;\n }\n }\n \n \n \n for(int i = 0; i <26; i++){\n if(upperCase[i]%2 ==0){\n ans += upperCase[i];\n }else{\n if(isFirstOdd == false){\n ans += upperCase[i]; \n isFirstOdd = true;\n }\n else\n ans += upperCase[i]-1;\n }\n }\n return ans;\n }\n}\n```\n**PYTHON**\n```\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n lowerCase = [0] * 26\n upperCase = [0] * 26\n \n for c in s:\n if ord(c) - 97 >= 0:\n lowerCase[ord(c) - 97] += 1\n else:\n upperCase[ord(c) - 65] += 1\n \n ans = 0\n isFirstOdd = False\n \n for i in range(26):\n if lowerCase[i] % 2 == 0:\n ans += lowerCase[i]\n else:\n if not isFirstOdd:\n ans += lowerCase[i]\n isFirstOdd = True\n else:\n ans += lowerCase[i] - 1\n \n for i in range(26):\n if upperCase[i] % 2 == 0:\n ans += upperCase[i]\n else:\n if not isFirstOdd:\n ans += upperCase[i]\n isFirstOdd = True\n else:\n ans += upperCase[i] - 1\n \n return ans\n```\n\n___\nComplexity Analysis\n___\n* **Time Complexity :-** BigO(N)\n* **Space Complexity :-** BigO(1) | 54 | 0 | ['C', 'Python', 'Java'] | 13 |
longest-palindrome | JAVA Solution. Simple and Clear, Using int[26] | java-solution-simple-and-clear-using-int-ivue | \n public int longestPalindrome(String s) {\n int[] lowercase = new int[26];\n int[] uppercase = new int[26];\n int res = 0;\n fo | markieff | NORMAL | 2016-10-02T17:22:18.738000+00:00 | 2018-10-21T17:56:36.276958+00:00 | 19,002 | false | \n public int longestPalindrome(String s) {\n int[] lowercase = new int[26];\n int[] uppercase = new int[26];\n int res = 0;\n for (int i = 0; i < s.length(); i++){\n char temp = s.charAt(i);\n if (temp >= 97) lowercase[temp-'a']++;\n else uppercase[temp-'A']++;\n }\n for (int i = 0; i < 26; i++){\n res+=(lowercase[i]/2)*2;\n res+=(uppercase[i]/2)*2;\n }\n return res == s.length() ? res : res+1;\n \n } | 46 | 2 | [] | 14 |
longest-palindrome | Python, C++,Java,||Faster than 100%||Short-Simple-Solution||BeginnerLevel | python-cjavafaster-than-100short-simple-oiwit | Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome.\n___\n__\nQ | Anos | NORMAL | 2022-10-18T17:07:57.754458+00:00 | 2022-10-18T17:07:57.754506+00:00 | 10,367 | false | ***Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome*.**\n___________________\n_________________\n***Q409. Longest Palindrome***\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\u2705 **Python Code** :\n```\nclass Solution:\n def longestPalindrome(self, s: str) -> int:\n res = 0\n for i in collections.Counter(s).values():\n res += i // 2 * 2\n return min(res+1, len(s))\n```\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\n\u2705 **Java Code** :\n```\nclass Solution {\n public int longestPalindrome(String s) {\n int[] count = new int[256];\n int odds = 0;\n for (int v = 0; v < s.length(); v++) {\n char currChar = s.charAt(v);\n count[currChar] += 1;\n odds += (count[currChar] & 1) == 1 ? 1 : -1;\n }\n return s.length() - odds + (odds > 0 ? 1 : 0);\n }\n}\n```\n\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\u2705 **C++ Code** :\n```\nclass Solution {\npublic:\n int longestPalindrome(const string &s) \n {\n int count[128]{};\n for (auto c : s) \n ++count[c];\n for (auto num : count) \n count[0] += num & 1;\n return s.size() - count[0] + (count[0] > 0);\n }\n};\n```\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\nIf you like the solution, please upvote \uD83D\uDD3C\nFor any questions, or discussions, comment below. \uD83D\uDC47\uFE0F\n | 44 | 1 | ['C', 'Python', 'Java'] | 8 |
longest-palindrome | 409. Longest Palindrome: Java Solution | 409-longest-palindrome-java-solution-by-0ykkw | Input:\n\n\nExplaination:\n\n\n\n\nOutput:\n\n\n\n\n\n\nclass Solution {\n\tpublic int longestPalindrome(String s) {\n\t\tif (s == null || s.length() == 0){\n | isalonisharma | NORMAL | 2021-11-27T16:23:30.062906+00:00 | 2023-11-28T17:05:10.669113+00:00 | 4,084 | false | Input:\n\n\nExplaination:\n\n\n\n\nOutput:\n\n\n\n\n\n```\nclass Solution {\n\tpublic int longestPalindrome(String s) {\n\t\tif (s == null || s.length() == 0){\n return 0;\n }\n\t\tHashSet<Character> hs = new HashSet<Character>();\n\t\tint count = 0;\n\t\tfor (int i = 0; i < s.length(); i++) {\n\t\t\tif (hs.contains(s.charAt(i))) {\n\t\t\t\ths.remove(s.charAt(i));\n\t\t\t\tcount++;\n\t\t\t} else {\n\t\t\t\ths.add(s.charAt(i));\n\t\t\t}\n\t\t}\n\t\tif (!hs.isEmpty()){\n return count * 2 + 1;\n }\n\t\treturn count * 2;\n\t}\n}\n```\n\nIf it helped, please UPVOTE. Happy Coding and keep up the good work.\nFeel free to give your suggestions or correct me in the comments.\nThanks for reading.\uD83D\uDE43 | 41 | 0 | ['Java'] | 7 |
longest-palindrome | c++ using hashmap | c-using-hashmap-by-aravindasai-vnka | \nclass Solution {\npublic:\n int longestPalindrome(string s) {\n unordered_map<char,int> map;\n for(int i=0;i<s.length();i++){\n ma | aravindasai | NORMAL | 2021-06-28T14:53:51.707101+00:00 | 2021-06-28T14:53:51.707149+00:00 | 3,030 | false | ```\nclass Solution {\npublic:\n int longestPalindrome(string s) {\n unordered_map<char,int> map;\n for(int i=0;i<s.length();i++){\n map[s[i]]++;\n }\n int cnt=0;\n for(auto i:map){\n if(i.second%2!=0){\n cnt++;\n }\n }\n if(cnt>1){\n return s.length()-cnt+1;\n }\n return s.length();\n }\n};\n``` | 37 | 0 | ['C'] | 9 |
longest-palindrome | JavaScript Solution | javascript-solution-by-deadication-4xe4 | \nvar longestPalindrome = function(s) {\n const set = new Set();\n let count = 0;\n \n for (const char of s) {\n if (set.has(char)) {\n\t\t\t | Deadication | NORMAL | 2020-08-14T17:00:44.137052+00:00 | 2020-08-14T17:01:39.196609+00:00 | 3,776 | false | ```\nvar longestPalindrome = function(s) {\n const set = new Set();\n let count = 0;\n \n for (const char of s) {\n if (set.has(char)) {\n\t\t\tcount += 2;\n set.delete(char);\n } \n\t\telse {\n set.add(char);\n }\n }\n\n return count + (set.size > 0 ? 1 : 0);\n};\n``` | 34 | 0 | ['JavaScript'] | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.