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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
element-appearing-more-than-25-in-sorted-array | easy c++ code🔥🔥💯 | easy-c-code-by-aboelanwar7-n4do | 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 | Aboelanwar7 | NORMAL | 2023-12-11T00:16:01.028080+00:00 | 2023-12-11T00:16:01.028099+00:00 | 362 | 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 int findSpecialInteger(vector<int>& arr) {\n int n = arr.size();\n if(n==1)return arr[0];\n int max = arr[0];\n int cnt = 1;\n for (int i = 1;i<n;i++) {\n if (arr[i] == max) {\n cnt++;\n if (cnt>n/4)\n return max;\n } else {\n max = arr[i];\n cnt = 1;\n }\n }\n return 0;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
element-appearing-more-than-25-in-sorted-array | Brute force and Optimised Both Solution (Beats 100%) | brute-force-and-optimised-both-solution-1pjt9 | 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 | Yashrajsingh282 | NORMAL | 2023-10-29T15:06:05.222539+00:00 | 2023-10-29T15:06:05.222565+00:00 | 112 | 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 public int findSpecialInteger(int[] arr) {\n\n // **** Time Complexity O(n2)*****\n // int len = arr.length;\n // int occurPercentage = len / 4;\n // for(int i=0;i<len;i++){\n // int count = 0;\n // for(int j=0;j<len;j++){\n // if(arr[i] == arr[j]){\n // count ++;\n // }\n // if(count > occurPercentage){\n // return arr[i];\n // }\n // }\n // }\n // return -1;\n\n\n /* **** OPTIMISED SOLUTION ****** */\n int len = arr.length;\n int occurPercentage = len / 4;\n int count = 0;\n int prev = -1;\n for(int val : arr){\n if(val == prev){\n count++;\n } else {\n prev = val;\n count = 1;\n }\n if(count > occurPercentage) return val;\n }\n return -1;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
element-appearing-more-than-25-in-sorted-array | ✅✅C++ Easy solution || Simple || No extra space | c-easy-solution-simple-no-extra-space-by-whpd | EXPLANATION\nHere we iterated through the given arr vector and checked if any number\'s frequency is greater than or equal to n/4+1. \nSo we return that number. | praegag | NORMAL | 2023-09-01T06:17:32.180973+00:00 | 2023-09-01T06:18:13.456196+00:00 | 152 | false | # EXPLANATION\nHere we iterated through the given **arr** vector and checked if any number\'s frequency is greater than or equal to **n/4+1**. \nSo we return that number.\n# SOLUTION\n```\nclass Solution {\npublic:\n int findSpecialInteger(vector<int>& arr) {\n int n=arr.size();\n int c=1,num=arr[0];\n double m_c=n/4+1;\n for(int i=1;i<n;i++){\n if(arr[i]==num)\n c++;\n else\n c=1,num=arr[i];\n if(c>=m_c)\n return arr[i];\n }\n return arr[0];\n }\n};\n``` | 2 | 0 | ['Array', 'C++'] | 1 |
element-appearing-more-than-25-in-sorted-array | Beginner friendly approach in Java | beginner-friendly-approach-in-java-by-he-940v | 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 | Hemuuu | NORMAL | 2023-06-22T07:50:03.032012+00:00 | 2023-06-22T07:50:03.032041+00:00 | 83 | 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 public int findSpecialInteger(int[] arr) {\n int n =arr.length;\n int c = 0;\n if(n==1){\n return arr[0];\n }\n for(int i=0;i<n-n/4;i++){\n if(arr[i]==arr[i+n/4]){\n c = arr[i];\n }\n }\n return c; \n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
element-appearing-more-than-25-in-sorted-array | Beginner friendly approach in java | beginner-friendly-approach-in-java-by-st-kx7r | Intuition\n Describe your first thoughts on how to solve this problem. \nI thought of calculating freaquency of all elements ,then divide each element\'s freque | starryvaibh | NORMAL | 2023-01-26T16:20:37.550699+00:00 | 2023-01-26T16:20:37.550760+00:00 | 503 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI thought of calculating freaquency of all elements ,then divide each element\'s frequency with length of array. If the percentage is >0.25 , then simply return that element.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution {\n public int findSpecialInteger(int[] arr) {\n int n=arr.length;\n HashMap<Integer,Integer> mp=new HashMap<>();\n for(int i:arr)\n mp.put(i,mp.getOrDefault(i,0)+1);\n for(int key:mp.keySet())\n {\n int f=mp.get(key);\n float percent=(float)f/(float)n;\n if(percent>0.25)\n return key;\n } \n return -1;\n }\n}\n``` | 2 | 0 | ['Hash Table', 'Hash Function', 'Java'] | 0 |
element-appearing-more-than-25-in-sorted-array | Simple Approach Python3 Easy | simple-approach-python3-easy-by-krish221-xpr2 | Intuition\n The question is to find the element that has a frequency greater than 25% and there exists only one such element. So it should be the element with g | krish2213 | NORMAL | 2023-01-19T14:19:45.546318+00:00 | 2023-01-19T14:19:45.546375+00:00 | 107 | false | # Intuition\n<!-- The question is to find the element that has a frequency greater than 25% and there exists only one such element. So it should be the element with greater frequency in simple elements. -->\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 findSpecialInteger(self, arr: List[int]) -> int:\n mydict = {}\n for i in set(arr):\n mydict[arr.count(i)] = i\n return mydict[max(mydict)]\n``` | 2 | 0 | ['Python3'] | 1 |
element-appearing-more-than-25-in-sorted-array | Sliding Window, easy to follow and 95%+ O(n) | sliding-window-easy-to-follow-and-95-on-76kg6 | Approach\nSliding Window\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n\n/**\n * @param {number[]} arr\n * @return {number}\ | hanbi58 | NORMAL | 2022-11-27T21:58:29.406054+00:00 | 2022-11-27T21:58:29.406079+00:00 | 235 | false | # Approach\nSliding Window\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\n/**\n * @param {number[]} arr\n * @return {number}\n */\nvar findSpecialInteger = function(arr) {\n for(let f=0,s=0;f<arr.length;f++){\n if(arr[s]===arr[f] && f-s+1> arr.length*0.25){return arr[s]}\n if(arr[s]!==arr[f]){s=f}\n }\n};\n``` | 2 | 0 | ['JavaScript'] | 1 |
element-appearing-more-than-25-in-sorted-array | easy c++ solution just using map and returning ans 😎😎😎 | easy-c-solution-just-using-map-and-retur-g311 | 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 | youdontknow001 | NORMAL | 2022-11-26T13:06:47.660086+00:00 | 2022-11-26T13:06:47.660117+00:00 | 981 | 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 int findSpecialInteger(vector<int>& arr) {\n map<int,int> mp;\n for(auto i:arr) mp[i]++;\n double aa = arr.size()*(25.00/100.00);\n // int ans = aa;\n cout<<aa<<endl;\n for(auto i:mp) if(i.second>aa) return i.first;\n return -1;\n }\n};\n``` | 2 | 1 | ['C++'] | 0 |
element-appearing-more-than-25-in-sorted-array | c++ | easy | short | c-easy-short-by-venomhighs7-pp9y | \n# Code\n\nclass Solution {\npublic:\n int findSpecialInteger(vector<int>& arr) {\n int sz = arr.size();\n vector<int> candidates = {arr[sz/4] | venomhighs7 | NORMAL | 2022-10-09T12:09:44.224730+00:00 | 2022-10-09T12:09:44.224756+00:00 | 780 | false | \n# Code\n```\nclass Solution {\npublic:\n int findSpecialInteger(vector<int>& arr) {\n int sz = arr.size();\n vector<int> candidates = {arr[sz/4], arr[sz/2], arr[sz*3/4]};\n for (auto cand : candidates) {\n auto st = lower_bound(arr.begin(), arr.end(), cand);\n auto ed = upper_bound(arr.begin(), arr.end(), cand);\n if (4 * (distance(st, ed)) > sz)\n return cand;\n }\n return -1;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
element-appearing-more-than-25-in-sorted-array | JS very easy solution | js-very-easy-solution-by-kunkka1996-ypok | \nvar findSpecialInteger = function(arr) {\n if (arr.length === 1) return arr[0];\n let count = 1;\n for (let i = 1; i < arr.length; i++) {\n if | kunkka1996 | NORMAL | 2022-10-04T05:10:07.786592+00:00 | 2022-10-04T05:10:07.786636+00:00 | 605 | false | ```\nvar findSpecialInteger = function(arr) {\n if (arr.length === 1) return arr[0];\n let count = 1;\n for (let i = 1; i < arr.length; i++) {\n if (arr[i] === arr[i-1]) {\n count++;\n } else {\n count = 1;\n }\n if (count > arr.length/4) return arr[i];\n }\n};\n``` | 2 | 0 | ['JavaScript'] | 1 |
element-appearing-more-than-25-in-sorted-array | A simple solution in Java (0 ms) | a-simple-solution-in-java-0-ms-by-toshpo-yssq | \nclass Solution {\n public int findSpecialInteger(int[] arr) {\n \n int target = arr.length / 4;\n \n for(int i = 0, count = 1; | toshpolaty | NORMAL | 2022-09-14T12:23:07.137169+00:00 | 2022-09-14T12:23:07.137213+00:00 | 339 | false | ```\nclass Solution {\n public int findSpecialInteger(int[] arr) {\n \n int target = arr.length / 4;\n \n for(int i = 0, count = 1; i < arr.length - 1; i++){\n if(arr[i] == arr[i+1]){\n count++;\n if(count > target)\n return arr[i];\n }else\n count = 1;\n }\n return arr[0];\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
element-appearing-more-than-25-in-sorted-array | Short python solution uses bisect. O(logn). | short-python-solution-uses-bisect-ologn-bdvbb | The function bisect locate the insertion point for x in a to maintain sorted order.\n\nThe idea was that the special number must appear in atleast quarter of th | sezio | NORMAL | 2022-03-06T20:53:30.474055+00:00 | 2022-04-21T16:14:49.512647+00:00 | 360 | false | The function bisect locate the insertion point for x in a to maintain sorted order.\n\nThe idea was that the special number must appear in atleast quarter of the array.\n\n```\nclass Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n n = len(arr)\n n_4th = n / 4\n candidates_loc = [n//4, n//2, n * 3 // 4]\n for loc in candidates_loc:\n idx1 = bisect_left(arr, arr[loc])\n idx2 = bisect_right(arr, arr[loc])\n if idx2 - idx1 > n_4th:\n return arr[loc]\n``` | 2 | 0 | ['Python', 'Python3'] | 0 |
element-appearing-more-than-25-in-sorted-array | Easy python solution | easy-python-solution-by-vistrit-ymnp | \ndef findSpecialInteger(self, arr: List[int]) -> int:\n n=len(arr)//4\n c=Counter(arr)\n for i in arr:\n if c[i]>n:\n | vistrit | NORMAL | 2021-11-20T04:24:09.335941+00:00 | 2021-11-20T04:24:09.335974+00:00 | 211 | false | ```\ndef findSpecialInteger(self, arr: List[int]) -> int:\n n=len(arr)//4\n c=Counter(arr)\n for i in arr:\n if c[i]>n:\n return i\n``` | 2 | 0 | ['Python', 'Python3'] | 0 |
element-appearing-more-than-25-in-sorted-array | Java 100% fast with comments | java-100-fast-with-comments-by-girish13-n32d | Java Code\n\n\nclass Solution {\n public int findSpecialInteger(int[] arr) {\n \n // store the value of (1/4)th of array size\n int coun | girish13 | NORMAL | 2021-06-02T11:37:01.169899+00:00 | 2021-06-02T11:38:32.716347+00:00 | 133 | false | **Java Code**\n\n```\nclass Solution {\n public int findSpecialInteger(int[] arr) {\n \n // store the value of (1/4)th of array size\n int count = arr.length / 4;\n \n for(int i = 1; i < arr.length; i++){ \n \n // if the consecutive elements match\n if(arr[i] == arr[i-1]){\n\t\t\t\t // decrement the count\n\t\t\t\t // if count becomes <= 0, then that element is occuring 25% time in the array\n if(--count <= 0)\n return arr[i];\n }\n \n // if the consecutive elements do not match\n // start counting 25% again for the new element arr[i]\n else{\n count = arr.length / 4;\n }\n }\n \n // default case if single element in the array \n return arr[0];\n }\n}\n```\n\n**Please `UPVOTE \uD83D\uDD3C` if like the code \uD83D\uDE04** | 2 | 0 | [] | 0 |
element-appearing-more-than-25-in-sorted-array | python easy!! | python-easy-by-meganath-agng | \tclass Solution:\n\t\tdef findSpecialInteger(self, arr: List[int]) -> int:\n\t\t\ta=len(arr)//4\n\t\t\tx=list(set(arr))\n\t\t\tfor i in x:\n\t\t\t\tif arr.coun | meganath | NORMAL | 2021-05-26T11:42:32.950159+00:00 | 2021-05-26T11:42:32.950201+00:00 | 104 | false | \tclass Solution:\n\t\tdef findSpecialInteger(self, arr: List[int]) -> int:\n\t\t\ta=len(arr)//4\n\t\t\tx=list(set(arr))\n\t\t\tfor i in x:\n\t\t\t\tif arr.count(i)>a:\n\t\t\t\t\treturn(i) | 2 | 0 | [] | 1 |
element-appearing-more-than-25-in-sorted-array | Java solution faster than 100% with explanation | java-solution-faster-than-100-with-expla-nb6n | This is a pretty simple solution, we have two variables num and counter. \n\nnum is used for checking whether arr[i] is equal to the character before it, and co | nathannaveen | NORMAL | 2021-01-14T01:21:38.773893+00:00 | 2021-01-14T01:21:38.773920+00:00 | 191 | false | This is a pretty simple solution, we have two variables `num` and `counter`. \n\n`num` is used for checking whether `arr[i]` is equal to the character before it, and counter is used for telling how many characters before are equal to `arr[i]`.\n\nWhen `arr[i]` is not equal to `num` then we check whether `counter > arr.length/4`. *(Notice that it is `>` and not `>=` because Java always floors divition)* if so then return `num` but the code can also return `arr[i]`.\n\nNext we make `num = arr[i]` because `num` has to become the new number, and we restart `counter`.\n\nAnd otherwise `arr[i]` is equal to `num` then we can just add `1` to `counter`.\n\n```\npublic int findSpecialInteger(int[] arr) {\n\tint counter = 0;\n\tint num = 0;\n\n\tfor (int i = 0; i < arr.length; i++) {\n\t\tif (arr[i] != num){\n\t\t\tif (counter > arr.length/4) return num;\n\t\t\tnum = arr[i];\n\t\t\tcounter = 1;\n\t\t}\n\t\telse counter ++;\n\t}\n\treturn num;\n}\n``` | 2 | 0 | ['Java'] | 0 |
element-appearing-more-than-25-in-sorted-array | C++ solution | Time: O(N), Space: O(1) | c-solution-time-on-space-o1-by-vasu-the-11jf3 | \nclass Solution {\npublic:\n int findSpecialInteger(vector<int>& arr) {\n \n int count=1;\n for(int i=1; i<arr.size(); i++){\n | vasu-the-sharma | NORMAL | 2021-01-01T19:03:04.604316+00:00 | 2021-01-01T19:03:04.604349+00:00 | 309 | false | ```\nclass Solution {\npublic:\n int findSpecialInteger(vector<int>& arr) {\n \n int count=1;\n for(int i=1; i<arr.size(); i++){\n if(arr[i]==arr[i-1]){\n count++;\n }else{\n if(count > arr.size()/4)\n return arr[i-1];\n else\n count=1;\n }\n }\n return arr[arr.size()-1];\n }\n};\n``` | 2 | 0 | ['C', 'C++'] | 0 |
element-appearing-more-than-25-in-sorted-array | C++ Solution || No map, no counter || 16ms | c-solution-no-map-no-counter-16ms-by-dan-0vqy | \nclass Solution {\npublic:\n int findSpecialInteger(vector<int>& arr) {\n int len = arr.size();\n int times = len / 4;\n for (int i = 0 | dannymmc | NORMAL | 2020-12-26T22:29:13.781343+00:00 | 2020-12-26T22:29:13.781383+00:00 | 96 | false | ```\nclass Solution {\npublic:\n int findSpecialInteger(vector<int>& arr) {\n int len = arr.size();\n int times = len / 4;\n for (int i = 0; i + times < len; i++) {\n if (arr[i] == arr[i + times])\n return arr[i];\n }\n return -1;\n }\n};\n``` | 2 | 0 | [] | 0 |
element-appearing-more-than-25-in-sorted-array | Easy and Fast JavaScript | easy-and-fast-javascript-by-fl4sk-5761 | \n\nconst findSpecialInteger = arr => {\n if(arr.length == 1)\n return arr[0];\n \n const maxCount = arr.length/4;\n let count = 1;\n \n for(let i = 1 | fl4sk | NORMAL | 2020-11-25T03:58:09.906351+00:00 | 2020-11-25T03:58:09.906388+00:00 | 185 | false | ```\n\nconst findSpecialInteger = arr => {\n if(arr.length == 1)\n return arr[0];\n \n const maxCount = arr.length/4;\n let count = 1;\n \n for(let i = 1; i < arr.length; i++){\n if(arr[i] == arr[i-1]){\n count++;\n if (count > maxCount)\n return arr[i];\n }\n else\n count = 1;\n } \n};\n\n``` | 2 | 0 | ['JavaScript'] | 0 |
element-appearing-more-than-25-in-sorted-array | faster than 100% java submissions | faster-than-100-java-submissions-by-athi-kkxd | \nclass Solution {\n public int findSpecialInteger(int[] arr) {\n int len = arr.length;\n len = len/4;\n int count = 0;\n int min | athirasabu | NORMAL | 2020-09-28T13:59:28.709356+00:00 | 2020-09-28T13:59:28.709388+00:00 | 66 | false | ```\nclass Solution {\n public int findSpecialInteger(int[] arr) {\n int len = arr.length;\n len = len/4;\n int count = 0;\n int min = arr[0];\n for(int i = 0 ; i < arr.length ; ){\n while(i < arr.length && min == arr[i] && count <= len){\n i++; \n count++;\n }\n if(count > len) return arr[i-1];\n else{\n \n count = 0;\n min = arr[i];\n \n \n }\n }\n return -1; \n }\n}\n``` | 2 | 0 | [] | 0 |
element-appearing-more-than-25-in-sorted-array | Python one line solution | python-one-line-solution-by-yixizhou-hkca | \nclass Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n return [x for x in arr if arr.count(x) > len(arr)/4][0]\n | yixizhou | NORMAL | 2020-08-31T19:17:50.785444+00:00 | 2020-08-31T19:17:50.785489+00:00 | 114 | false | ```\nclass Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n return [x for x in arr if arr.count(x) > len(arr)/4][0]\n``` | 2 | 0 | [] | 0 |
element-appearing-more-than-25-in-sorted-array | Java Solution 100% in both space and time | java-solution-100-in-both-space-and-time-e8nj | \'\'\'\nclass Solution {\n public int findSpecialInteger(int[] arr) \n {\n int count=1;\n for(int i=0;i(int)(arr.length/4))\n | adarsh_goswami | NORMAL | 2020-04-17T13:02:56.713264+00:00 | 2020-04-17T13:02:56.713317+00:00 | 125 | false | \'\'\'\nclass Solution {\n public int findSpecialInteger(int[] arr) \n {\n int count=1;\n for(int i=0;i<arr.length-1;i++)\n {\n if(arr[i]==arr[i+1]) \n count++;\n else\n count=1;\n if(count>(int)(arr.length/4))\n return arr[i];\n \n }\n return arr[0];\n }\n}\n\'\'\' | 2 | 0 | [] | 1 |
maximize-the-minimum-game-score | C++ Binary Search | c-binary-search-by-bramar2-81yq | Approach
Binary search from 1 to 1e18.
Loop through the points and add up the needed operations.
You can't just stay at one index and keep adding, you HAVE to m | bramar2 | NORMAL | 2025-02-09T03:40:09.274666+00:00 | 2025-02-10T09:47:06.975206+00:00 | 1,693 | false | # Approach
- Binary search from 1 to 1e18.
- Loop through the points and add up the needed operations.
- You can't just stay at one index and keep adding, you HAVE to move. So, you move between $i$ and $i + 1$ (because you know $i - 1$ has already been processed which means it is greater than val). In this case, you will need $2x-1$ ops, where $x = \lceil\frac{A_i}{val}\rceil$. Then, you incur $x - 1$ ops on $i + 1$, so store that information in a variable `transfer`.
- One more thing, if after `transfer` ops happen, the number is already good. Then, increment `skipAdd`. Once you encounter something that NEEDS operations, you add `skipAdd` to `totalOps`.
- Why? Take a look at this array $[1, 10^{18}, 10^{18}, 10^{18},10^{18},10^{18}, 1]$. If you don't account for this, you will skip the $10^{18}$ numbers with 0 ops. Also technically, `skipAdd` could be a boolean instead of an int because it is always either 0 or 1.
- Be careful of overflow:
$$transfer * point \ge val \newline
transfer \ge \frac{val}{points_i}$$
Instead of checking $transfer * points_i \ge val$, check $transfer \ge \frac{val}{points_i}$.
# Example
`points = [1,2,3]`
`target = 10`
| Index | Before | After | Explanation
| - | - | - | - |
| 0 | [0, 0, 0] | [10, 18, 0] | Total = 0, skip_add = 0.<br><br> We're at index `-1`. Move to index `0` then move between index `1` and `0` until `arr[0] >= 10`. 10 ops on index `0`, 9 ops on index `1` for a total of 19 ops. <br><br>Total = 19, skip_add = 0
| 1 | [10, 18, 0] | [10, 18, 0] | Total = 19, skip_add = 0. <br><br>We're at index `0`. Don't do anything because `arr[1] >= 10`. Since we skip this number, we set skip_add to 1.<br><br> Total = 19, skip_add = 1
| 2 | [10, 18, 0] | [10, 18, 12] | Total = 19, skip_add = 1. <br><br><br><br> We're at index `0`. We need to do 4 ops on index `2` because `3*4 >= target (10)`. We need to travel from index `0` to `2`, this is what skip_add is for. Since we skipped before, we need to add one more operation. 1 op for skip_add, 4 ops on index `2`, 3 ops on index `1` makes the total 8 ops. <br><br>Total = 27, skip_add = 0
So in the end, you need a minimum of 27 operations for ans = 10.
# Complexity
- Time complexity: $O(n*log(10^{18}))=O(n)$
- Space complexity: $O(1)$
# Code
```cpp []
class Solution {
public:
long long maxScore(vector<int>& points, int m) {
int n = points.size();
if(m < n) return 0;
auto can = [&](long long val) -> bool {
long long total = 0, transfer = 0, skipAdd = 0;
for(int i = 0; i < n && total <= m; i++) {
int point = points[i];
long long necessary = (val + point - 1) / point;
if(transfer >= necessary) {
transfer = 0;
skipAdd++;
}else {
long long p = transfer * point;
long long ops = (((val - p) + point - 1) / point);
total += 2*ops - 1;
total += skipAdd;
transfer = max(ops - 1, 0LL);
skipAdd = 0;
}
}
return total <= m;
};
long long l = 1, r = 1e18, ans = 0;
while(l <= r) {
long long m = l + (r-l)/2;
if(can(m)) {
ans = m;
l = m + 1;
}else {
r = m - 1;
}
}
return ans;
}
};
``` | 14 | 0 | ['C++'] | 5 |
maximize-the-minimum-game-score | Binary Search | Short Code | Beginner Friendly | Example Walkthrough | binary-search-beginner-friendly-example-xp33j | Intuition
🎯 Key Observation:
To maximize the minimum value in the gameScore array after at most m moves, we must ensure every game’s score is raised to at least | shubham6762 | NORMAL | 2025-02-09T04:49:44.201454+00:00 | 2025-02-09T06:20:29.116598+00:00 | 820 | false |
## Intuition
- **🎯 Key Observation:**
To maximize the minimum value in the **gameScore** array after at most **m** moves, we must ensure every game’s score is raised to at least a target value **v**.
- For each game with point value **p**, we need at least ⌈**v/p**⌉ moves to raise its score to **v**.
- **Moving forward** (increase index) and **moving backward** (decrease index) incur extra move costs; roughly, to “fix” a game’s score you pay a cost of roughly **(2 × ops - 1)** moves.
- We use a **binary search** over possible target values **v** to determine the maximum achievable minimum score while ensuring the total moves do not exceed **m**.
---
## Example
Let’s take **points = [2, 4]** and **m = 3**. Our goal is to maximize the minimum value in **gameScore**.
| **Move** | **Action** | **Index** | **gameScore** | **Explanation** |
|:--------:|:---------------:|:---------:|:-----------------:|:-----------------------------------------|
| 1️⃣ | Increase index | 0 | [**2**, 0] | Added **2** from **points[0]** (2️⃣) |
| 2️⃣ | Increase index | 1 | [2, **4**] | Added **4** from **points[1]** (4️⃣) |
| 3️⃣ | Decrease index | 0 | [**4**, 4] | Added **2** again to gameScore[0] |
- **Minimum gameScore:** 4
- **Output:** **4** ✅
---
## Complexity
- **Time Complexity:** O(n · log(max_answer))
- **Space Complexity:** O(n)
---
```cpp []
using ll = long long;
bool possible(ll t, const vector<int>& pts, int M) {
ll mv = 0, ext = 0, bon = 0;
for (int p : pts) {
ll req = (t + p - 1LL) / p;
if (ext >= req) { ext = 0; bon++; }
else { ll d = req - ext; mv += 2 * d - 1 + bon; ext = d - 1; bon = 0; }
if (mv > M) return false;
}
return true;
}
class Solution {
public:
long long maxScore(vector<int>& pts, int M) {
if (M < pts.size()) return 0;
ll lo = 1, hi = 1e18, ans = 0;
while (lo <= hi) {
ll mid = lo + (hi - lo) / 2;
if (possible(mid, pts, M)) { ans = mid; lo = mid + 1; }
else hi = mid - 1;
}
return ans;
}
};
```
```java []
class Solution {
private boolean possible(long t, int[] pts, int M) {
long mv = 0, ext = 0, bon = 0;
for (int p : pts) {
long req = (t + p - 1L) / p;
if (ext >= req) { ext = 0; bon++; }
else { long d = req - ext; mv += 2 * d - 1 + bon; ext = d - 1; bon = 0; }
if (mv > M) return false;
}
return true;
}
public long maxScore(int[] pts, int M) {
if (M < pts.length) return 0;
long lo = 1, hi = (long)1e18, ans = 0;
while (lo <= hi) {
long mid = lo + (hi - lo) / 2;
if (possible(mid, pts, M)) { ans = mid; lo = mid + 1; }
else hi = mid - 1;
}
return ans;
}
}
```
```python []
class Solution:
def possible(self, t, pts, M):
mv = ext = bon = 0
for p in pts:
req = -(-t // p)
if ext >= req: ext, bon = 0, bon + 1
else:
d = req - ext; mv += 2 * d - 1 + bon; ext, bon = d - 1, 0
if mv > M: return False
return True
def maxScore(self, pts, M):
if M < len(pts): return 0
lo, hi, ans = 1, 10**18, 0
while lo <= hi:
mid = lo + (hi - lo) // 2
if self.possible(mid, pts, M):
ans, lo = mid, mid + 1
else:
hi = mid - 1
return ans
```
```javascript []
function possible(t, pts, M) {
let mv = 0, ext = 0, bon = 0;
for (const p of pts) {
const req = Math.floor((t + p - 1) / p);
if (ext >= req) { ext = 0; bon++; }
else { let d = req - ext; mv += 2 * d - 1 + bon; ext = d - 1; bon = 0; }
if (mv > M) return false;
}
return true;
}
var maxScore = function(pts, M) {
if (M < pts.length) return 0;
let lo = 1, hi = 1e18, ans = 0;
while (lo <= hi) {
let mid = lo + Math.floor((hi - lo) / 2);
if (possible(mid, pts, M)) { ans = mid; lo = mid + 1; }
else hi = mid - 1;
}
return ans;
};
```
---
# *Happy coding! 🎉*
--- | 13 | 2 | ['Binary Search', 'Python', 'C++', 'Java', 'JavaScript'] | 1 |
maximize-the-minimum-game-score | [Java/C++/Python] Greedy + Binary Search | javacpython-greedy-binary-search-by-lee2-8b3m | [Java/C++/Python] Greedy + Binary SearchExplanationcheck function will check the steps necessay to make game score to target.
If gameScore[i] doesn't reach the | lee215 | NORMAL | 2025-02-10T07:30:50.236815+00:00 | 2025-02-10T07:30:50.236815+00:00 | 799 | false | [Java/C++/Python] Greedy + Binary Search
----------------------------------------------
# **Explanation**
`check` function will check the steps necessay to make game score to `target`.
If `gameScore[i]` doesn't reach the `target`,
we will move greedily by +1 then -1.
`k` is the number of move we reach at `A[i]`,
each time we will increment `k * 2 - 1` to the result `res`.
For example, if we need 3 of `A[0]`,
it takes `A[0], A[1], A[0], A[1], A[0]`,
which is 5 moves,
and we update `k = 2` for `A[1]`.
We binary search the result to find
the biggest `target` we can get.
# **Complexity**
Time `O(logm + logA)`
Space `O(1)`
<br>
```Java [Java]
public long maxScore(int[] A, int m) {
long l = 0, r = 1L * (m + 1) / 2 * A[0];
while (l < r) {
long mid = (l + r + 1) / 2;
if (check(A, mid, m)) {
l = mid;
} else {
r = mid - 1;
}
}
return l;
}
private boolean check(int[] A, long target, int m) {
long res = 0, k = 0;
int n = A.length;
for (int i = 0; i < n; ++i) {
if (i == n - 1 && 1L * k * A[i] >= target) break;
k = Math.max((target + A[i] - 1) / A[i] - k - 1, 0);
res += k * 2 + 1;
if (res > m) {
return false;
}
}
return true;
}
```
```C++ [C++]
long long maxScore(vector<int>& A, int m) {
long long l = 0, r = 1LL * (m + 1) / 2 * A[0];
while (l < r) {
long long mid = (l + r + 1) / 2;
if (check(A, mid, m)) {
l = mid;
} else {
r = mid - 1;
}
}
return l;
}
bool check(vector<int>& A, long long target, int m) {
long long res = 0, k = 0;
int n = A.size();
for (int i = 0; i < n; ++i) {
if (i == n - 1 && 1LL * k * A[i] >= target) break;
k = max((target + A[i] - 1) / A[i] - k - 1, 0LL);
res += k * 2 + 1;
if (res > m) {
return false;
}
}
return true;
}
```
```py [Python3]
def maxScore(self, A: List[int], m: int) -> int:
def check(target):
res = k = 0
for i in range(n):
if i == n - 1 and k * A[i] >= target: break
k = max(ceil(target / A[i]) - (k + 1), 0)
res += k * 2 + 1
if res > m:
return False
return res <= m
n = len(A)
l, r = 0, (m + 1) // 2 * A[0]
while l < r:
mid = (l + r + 1) // 2
if check(mid):
l = mid
else:
r = mid - 1
return l
```
| 6 | 0 | ['Binary Search', 'Greedy', 'Python', 'C++', 'Java', 'Python3'] | 3 |
maximize-the-minimum-game-score | [Python] Binary Search | python-binary-search-by-awice-v98w | Binary search for the answer. You have some req[] representing how many times you need to visit each cell i. Notice you need to visit every cell at least once | awice | NORMAL | 2025-02-09T05:49:28.616969+00:00 | 2025-02-09T05:49:28.616969+00:00 | 495 | false | Binary search for the answer. You have some `req[]` representing how many times you need to visit each cell `i`. Notice you need to visit every cell at least once.
Now consider at some time you are standing to the left of index `i`. You want to visit cell `i` `req[i]` times, so you enter (1) and then go to i+1 and back another `req[i] - 1` times. After this, the next cell is visited `req[i] - 1` times (if it doesn't exist, it doesn't affect the answer.) So `req[i + 1]` is decremented by `req[i] - 1`. We can show that this greedy approach works as walking away doesn't help.
# Code
```python3 []
class Solution:
def maxScore(self, A: List[int], M: int) -> int:
N = len(A)
def possible(bound):
req = [(bound + x - 1) // x for x in A]
steps = 0
for i, x in enumerate(req):
if x:
steps += 2 * x - 1
if i + 1 < N:
req[i + 1] = max(0, req[i + 1] - (req[i] - 1))
elif i < N - 1:
steps += 1
return steps <= M
lo, hi = 0, int(10**6 * M / N) + 1
while lo < hi:
mi = lo + hi + 1 >> 1
if possible(mi):
lo = mi
else:
hi = mi - 1
return lo
``` | 6 | 0 | ['Python3'] | 0 |
maximize-the-minimum-game-score | O(nlogn) || Binary Search + Greedy || Simple || Must Check | onlogn-binary-search-greedy-simple-must-asbuw | Complexity
Time complexity:
O(n.logn)
Space complexity:
O(n)Code | Priyanshu_pandey15 | NORMAL | 2025-02-14T10:50:24.016814+00:00 | 2025-02-14T10:50:24.016814+00:00 | 88 | false |
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
$$O(n.logn)$$
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
$$O(n)$$
# Code
```java []
class Solution {
static public long maxScore(int[] points, int m) {
boolean res = false;
long max = 0;
long start = 0, end = 1000000000000000l, mid = 0;
while(start <= end){
mid = start + (end - start) / 2l;
long[] temp = req(mid, points);
boolean iss = canBe(temp, m);
if(iss){
max = mid;
start = mid + 1l;
}else end = mid - 1l;
}
return max;
}
static long[] req(long x, int[] arr) {
int n = arr.length;
long[] ans = new long[n];
for (int i = 0; i < n; i++) {
long y = (x + (long)(arr[i] - 1)) / arr[i];
ans[i] = y;
}
return ans;
}
static boolean canBe(long[] arr, long m) {
long send = 1, total = 1;
int n = arr.length;
long tempSend = 0;
for (int i = 0; i < n; i++) {
tempSend = (arr[i]) - send;
if (i == n - 1) continue;
if (tempSend < 0) tempSend = 0;
total += (tempSend * 2l) + 1;
if (total > m && i < n - 2) return false;
send = tempSend + 1;
}
if (n >= 2) {
if (tempSend < 0) total--;
if (tempSend > 0) total += (tempSend * 2l);
}
return total <= m;
}
}
``` | 3 | 0 | ['Binary Search', 'Greedy'] | 0 |
maximize-the-minimum-game-score | C++ | Binary Search | Greedy | Solution with explanation | c-binary-search-greedy-solution-with-exp-94aa | ref: https://www.zerotoexpert.blog/p/weekly-contest-436SolutionIn this problem, we should find the maximum of minimum possible value after, at most, m moves. In | a_ck | NORMAL | 2025-02-09T08:38:07.006918+00:00 | 2025-02-09T08:38:07.006918+00:00 | 250 | false | ref: https://www.zerotoexpert.blog/p/weekly-contest-436
# Solution
In this problem, we should find the maximum of minimum possible value after, at most, m moves. In this problem, if you can make all points to K within m moves, then you can say that all points are over K-1, K-2, etc. So, we can simply check if random X is okay for the answer. If yes, we only need to check the values above X. Otherwise, check those below X.
Then, we need to solve the problem of whether it is possible to make all values larger than or equal to X if X is given. Now the X is given, we can calculate how many times we should visit every index.
- cnt[i] = `(X + points[i] -1) / points[i]`
Now, we can visit the index i greedily. No matter how far you go from i, you should visit the current index(i) at cnt[i] times. In this problem you should visit all indexes to get back to the index i and every move counts. So, we just can visit the current cnt[i] times first, then we can go to the next index.
- To visit index i, we can start from the previous index. [move `i-1` to `i`]
- And then, we should go to the next index and get back to the current as many times as needed. [move `i` to `i+1` and move `i+1` to `i`] * (`cnt[i]-1` times).
- We already visit once from the previous index, so we just need the `cnt[i] - 1` times visit more.
- In this case, we should reduce the cnt[i+1] by (`cnt[i]-1`).
- If cnt[i] ==0 , even though we don’t need to visit more, then we need to move to i to visit the i+1 index.
- However, if the cnt[i] == 0 and the i == n-1, which means that we don’t need any more visit after i, then we can stop moving.
# Code
```cpp []
class Solution {
public:
// Helper function to check if a given minimum value can be achieved
bool isPossible(vector<int>& points, long long targetValue, int maxMoves) {
int n = points.size();
vector<long long> requiredUpdates(n);
long long totalMoves = 0;
// Calculate how many times each index needs to be updated to reach targetValue
for (int i = 0; i < n; ++i) {
requiredUpdates[i] = (targetValue + points[i] - 1) / points[i]; // Ceiling division
// If previous index was updated, adjust current index accordingly
if (i > 0 && requiredUpdates[i - 1] > 0) {
totalMoves += 2 * requiredUpdates[i - 1] - 1;
requiredUpdates[i] = max(0LL, requiredUpdates[i] - (requiredUpdates[i - 1] - 1));
}
// Otherwise, if we are in the middle of the array, count a move
else if (i > 0 && i != n - 1) {
totalMoves++;
}
}
// Handle last index separately
if (requiredUpdates[n - 1] > 0) {
totalMoves += requiredUpdates[n - 1] * 2;
if (requiredUpdates[n - 2] > 0) {
totalMoves--; // Reduce one move if second last index was updated
}
}
return totalMoves <= maxMoves; // Check if we can achieve the target value within maxMoves
}
// Binary search to find the maximum possible minimum value
long long maxScore(vector<int>& points, int m) {
long long left = 1, right = 1e15, answer = 0;
while (left <= right) {
long long mid = left + (right - left) / 2;
// Check if it's possible to maintain a minimum score of 'mid'
if (isPossible(points, mid, m)) {
answer = mid; // Store the valid answer
left = mid + 1; // Try for a higher minimum value
} else {
right = mid - 1; // Reduce the search space
}
}
return answer; // Maximum minimum possible value
}
};
``` | 3 | 0 | ['C++'] | 0 |
maximize-the-minimum-game-score | Simple Binary Search: O(n*60) | simple-binary-search-on60-by-tunt6-b7iz | IntuitionMaximize / minimize -> BSApproachUnderstanding the problem:We need to maximize the value while ensuring the total moves don’t exceed m.
The answer lies | tunt6 | NORMAL | 2025-02-09T05:58:24.551098+00:00 | 2025-02-09T10:19:56.145378+00:00 | 276 | false | # Intuition
Maximize / minimize -> BS
# Approach
## Understanding the problem:
We need to maximize the value while ensuring the total moves don’t exceed m.
The answer lies between 1 and Long.MAX_VALUE, so we can use Binary Search (BS) to efficiently find the best possible value.
## Binary Search Implementation:
1. Use BS on the answer to find the maximum value minV that can be achieved within m moves.
2. Checking Feasibility (check(minV, points, m))
- Step 1: Precompute the cnt array, where cnt[i] stores the minimum number of times points[i] needs to be selected to reach at least minV.
Formula: cnt[i] = (minV + points[i] - 1) / points[i]
- Step 2: Loop through points[]:
For each points[i], we need at least pm = max(0, cnt[i] - 1) extra selections.
Moving forward requires 1 + 2 * pm moves.
If total move > m, return false.
3. Final Decision:
- If check(minV, points, m) == true, increase minV in Binary Search to find a larger possible value.
- Otherwise, reduce minV to stay within the move limit.
# Complexity
- Time complexity: O(n * log(Long.MAX_VALUE)): loop points with BS times
- Space complexity: O(n): stores cnt array
# Code
```Java []
class Solution {
public long maxScore(int[] points, int m) {
long l = 0;
long r = Long.MAX_VALUE;
long ans = 0;
while(l <= r) {
long mid = (l+r) / 2;
if(check(mid, points, m)) {
ans = mid;
l = mid+1;
} else {
r = mid-1;
}
}
return ans;
}
private boolean check(long minV, int[] points, int m) {
int n = points.length;
long[] cnt = new long[n + 1];
for(int i = 0; i < n; i++) {
cnt[i] = (long) ((minV + points[i] - 1) / points[i]);
}
long move = 0;
for(int i = 0; i < n; i++) {
if(i == n-1 && cnt[i] <= 0) {
break;
}
long pm = (cnt[i]-1 > 0 ? (cnt[i]-1) : 0);
move += 1 + pm * 2;
cnt[i+1] -= pm;
if(move > m) {
return false;
}
}
return move <= m;
}
}
```
```cpp []
class Solution {
public:
bool check(long long minV, vector<int>& points, int m) {
vector<long long> cnt;
for(int x : points) {
cnt.push_back((minV + x - 1) / x); // Calculate required moves
}
cnt.push_back(0); // Avoid out-of-bounds access
long long move = 0;
for(int i = 0; i < points.size(); i++) {
if(i == points.size() - 1 && cnt[i] <= 0) break;
long long pm = max(0LL, cnt[i] - 1); // Ensure non-negative
move += 1 + pm * 2; // Move + backtracking
if (i + 1 < cnt.size()) cnt[i+1] -= pm; // Prevent out-of-bounds
if(move > m) return false; // Early exit
}
return move <= m;
}
long long maxScore(vector<int>& points, int m) {
long long l = 0, r = 1e15, ans = 0; // Adjust upper bound
while(l <= r) {
long long mid = (l + r) / 2;
if(check(mid, points, m)) {
ans = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
return ans;
}
};
``` | 3 | 0 | ['C++', 'Java'] | 1 |
maximize-the-minimum-game-score | EASY JAVA SOLUTION USING BINARY SEARCH {PLZ UPVOTE ME GUYS} | easy-java-solution-using-binary-search-p-edh6 | IntuitionThe problem requires us to maximize the score while ensuring that the total operations do not exceed a given limit, m. Since increasing the score monot | TOURIST15789 | NORMAL | 2025-02-09T04:38:21.711691+00:00 | 2025-02-09T04:38:21.711691+00:00 | 256 | false | # Intuition
The problem requires us to maximize the score while ensuring that the total operations do not exceed a given limit, m. Since increasing the score monotonically requires more operations, we can leverage binary search to efficiently determine the maximum achievable score.
# Approach
Binary Search on Answer:
The answer lies between 1 and 10^18, so we use binary search to find the maximum score.
We check whether a given score val can be achieved within m operations using a helper function.
Helper Function (canAchieve)
This function iterates over the points array while keeping track of total operations used.
It computes the minimum number of operations required to achieve val using the given points.
If the total operations exceed m, we return false; otherwise, we return true.
Updating the Search Space:
If canAchieve(mid) is true, we update ans = mid and continue searching in the upper half (left = mid + 1).
Otherwise, we search in the lower half (right = mid - 1).
# Complexity
- Time complexity:
The binary search runs in O(log M) iterations, where M = 10^18.
The canAchieve function runs in O(n) for each binary search step.
Hence, the total time complexity is O(n log M).
- Space complexity:
We use only a few extra variables, leading to O(1) auxiliary space.
# Code
```java []
class Solution {
public long maxScore(int[] points, int m) {
int n = points.length;
if (m < n) return 0;
long left = 1, right = (long) 1e18, ans = 0;
while (left <= right) {
long mid = left + (right - left) / 2;
if (canAchieve(points, n, m, mid)) {
ans = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}
return ans;
}
private boolean canAchieve(int[] points, int n, int m, long val) {
long total = 0, transfer = 0, skipAdd = 0;
for (int i = 0; i < n && total <= m; i++) {
int point = points[i];
long necessary = (val + point - 1) / point;
if (transfer >= necessary) {
transfer = 0;
skipAdd++;
} else {
long p = transfer * (long) point;
long ops = ((val - p) + point - 1) / point;
total += 2 * ops - 1;
total += skipAdd;
transfer = Math.max(ops - 1, 0);
skipAdd = 0;
}
}
return total <= m;
}
}
``` | 3 | 1 | ['Binary Search', 'Java'] | 2 |
maximize-the-minimum-game-score | Python - Binary search | python-binary-search-by-wanderingcicada-7xay | IntuitionGuess and checkApproachHow do we know if a guess is possible? Try to set every score >= to your guess. In order to increase your score, you must move t | wanderingCicada | NORMAL | 2025-02-09T04:29:09.282086+00:00 | 2025-02-09T04:29:09.282086+00:00 | 192 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Guess and check
# Approach
<!-- Describe your approach to solving the problem. -->
How do we know if a guess is possible? Try to set every score >= to your guess. In order to increase your score, you must move to the next index and back. You could also move to the previous index and back but that's wasteful if you already settled the previous index.
# Complexity
- Time complexity:
- O(nlog(m * min(points))) ~ (O(nlog(n))) ish
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def maxScore(self, points: List[int], m: int) -> int:
def possible(count, m):
score = points[0]
m -= 1
# print(count)
for i in range(len(points)):
nextScore = 0
if score < count:
diff = count - score
moves = math.ceil(diff / points[i])
if m - (2 * moves) < 0:
return False
m -= 2 * moves
if i + 1 < len(points):
nextScore += points[i + 1] * moves
# print(scores, count, m)
if i + 1 < len(points):
if m <= 0 and nextScore < count:
return False
m -= 1
nextScore += points[i + 1]
score = nextScore
return True
if m < len(points):
return 0
low = 0
high = min(points) * m
# print(low, high)
while low < high:
middle = (low + high + 1) // 2
if possible(middle, m):
low = middle
else:
high = middle - 1
return low
``` | 3 | 0 | ['Python3'] | 1 |
maximize-the-minimum-game-score | only binary search c++ | only-binary-search-c-by-shivanshu0287-uuz3 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | shivanshu0287 | NORMAL | 2025-02-09T04:25:58.214451+00:00 | 2025-02-09T04:25:58.214451+00:00 | 132 | 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 {
using ll=long long;
bool solve(vector<int>&pt,ll m,int n,ll mini){
vector<ll>v(n+1,0);
for(int i=0;i<n;i++){
v[i]=ceil(mini/double(pt[i]));
}
int i=0;
v[0]--;
m--;
while(i<n){
if(v[i]<=0){
if(i==n-1)break;
if(i+1==n-1){
if(v[i+1]<=0)break;
}
v[i+1]--;
m--;
if(m<0)return 0;
i++;
continue;
}
if(m<2*v[i])return 0;
m-=2*v[i];
v[i+1]-=v[i];
v[i]=0;
}
return m>=0;
}
public:
long long maxScore(vector<int>& pt, int m) {
ll s=1,e=1e16;
while(s<=e){
ll mi=(e-s)/2+s;
if(solve(pt,m,pt.size(),mi)){
s=mi+1;
}else{
e=mi-1;
}
}
return e;
}
};
``` | 2 | 0 | ['C++'] | 0 |
maximize-the-minimum-game-score | easy cpp solution | easy-cpp-solution-by-tourist15789-gbzh | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | TOURIST15789 | NORMAL | 2025-02-09T04:14:28.316112+00:00 | 2025-02-09T04:14:28.316112+00:00 | 378 | 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:
long long maxScore(vector<int>& points, int m) {
int n = points.size();
if(m < n) return 0;
auto can = [&](long long val) -> bool {
long long total = 0, transfer = 0, skipAdd = 0;
for(int i = 0; i < n && total <= m; i++) {
int point = points[i];
long long necessary = (val + point - 1) / point;
if(transfer >= necessary) {
transfer = 0;
skipAdd++;
}else {
long long p = transfer * point;
long long ops = (((val - p) + point - 1) / point);
total += 2*ops - 1;
total += skipAdd;
transfer = max(ops - 1, 0LL);
skipAdd = 0;
}
}
return total <= m;
};
long long l = 1, r = 1e18, ans = 0;
while(l <= r) {
long long m = l + (r-l)/2;
if(can(m)) {
ans = m;
l = m + 1;
}else {
r = m - 1;
}
}
return ans;
}
};
``` | 2 | 0 | ['C++'] | 3 |
maximize-the-minimum-game-score | C++ | Binary Search + Greedy | c-binary-search-greedy-by-kena7-ht1a | Code | kenA7 | NORMAL | 2025-02-20T07:05:34.252907+00:00 | 2025-02-20T07:05:34.252907+00:00 | 21 | false |
# Code
```cpp []
class Solution {
public:
#define ll long long
bool possible(ll minS, int m, vector<int>& p)
{
int n=p.size();
vector<ll>count(n,0);
for(int i=0;i<n;i++)
{
count[i]=(minS/p[i])+(minS%p[i]!=0);
}
count[0]--;
m--;
int i=0,j=0;
while(i<n)
{
if(count[i]<=0)
{
i++;
}
else
{
if(j!=i)
{
m-=(i-j);
if(m<0)
return false;
count[i]--;
}
ll curr=count[i]*2;
if(m<curr)
return false;
m-=curr;
if(i<n-1)
count[i+1]-=count[i];
count[i]=0;
j=i;
i++;
}
}
return i>=n;
}
long long maxScore(vector<int>& p, int m)
{
ll mx=*max_element(p.begin(), p.end());
ll l=0,h=mx*m,res=0;
while(l<=h)
{
ll k=(l+h)/2;
if(possible(k,m,p))
{
res=k;
l=k+1;
}
else
h=k-1;
}
return res;
}
};
``` | 1 | 0 | ['C++'] | 0 |
maximize-the-minimum-game-score | 💥 Beats 100% on runtime [EXPLAINED] | beats-100-on-runtime-explained-by-r9n-xiz3 | IntuitionMaximize the minimum score we can achieve after making at most m moves. To do this, we need to find the best possible score by trying different values | r9n | NORMAL | 2025-02-15T04:43:28.072591+00:00 | 2025-02-15T04:43:28.072591+00:00 | 6 | false | # Intuition
Maximize the minimum score we can achieve after making at most m moves. To do this, we need to find the best possible score by trying different values and checking whether it's achievable within the m moves. We can utilize binary search to efficiently explore the range of possible scores and adjust the score based on whether it meets the conditions.
# Approach
Use binary search on the possible score and check for each candidate score if it’s achievable within m moves by simulating the moves and adjusting the index accordingly.
# Complexity
- Time complexity:
O(n * log(maxScore)), where n is the number of elements in the array and log(maxScore) comes from the binary search across possible scores.
- Space complexity:
O(1) since we only use a few variables to store intermediate values (no additional data structures like arrays or hashmaps).
# Code
```rust []
impl Solution {
pub fn max_score(a: Vec<i32>, m: i32) -> i64 {
let mut l = 0;
let mut r = 1i64 * (m as i64 + 1) / 2 * a[0] as i64;
while l < r {
let mid = (l + r + 1) / 2;
if Solution::check(&a, mid, m) {
l = mid;
} else {
r = mid - 1;
}
}
l
}
fn check(a: &Vec<i32>, target: i64, m: i32) -> bool {
let mut res = 0;
let mut k = 0;
let n = a.len();
for i in 0..n {
if i == n - 1 && (k as i64) * (a[i] as i64) >= target {
break;
}
k = std::cmp::max((target + a[i] as i64 - 1) / a[i] as i64 - k as i64 - 1, 0);
res += k * 2 + 1;
if res > m as i64 { // Convert `m` to `i64` here
return false;
}
}
true
}
}
``` | 1 | 0 | ['Binary Search', 'Greedy', 'Rust'] | 0 |
maximize-the-minimum-game-score | Test | test-by-fuckleetcode_bringolduiback-0j31 | test | fuckleetcode_BringOldUIBack | NORMAL | 2025-02-13T12:39:58.119046+00:00 | 2025-02-13T12:42:10.455708+00:00 | 27 | false | test | 1 | 0 | ['Python3'] | 0 |
maximize-the-minimum-game-score | Binary search on answer | binary-search-on-answer-by-vikas_dor-gwjt | Intuitionif X is the minimum in the game score array, then we need to make sure everyone should have atleast this valueThen we can say if we can acheive this wi | vikas_dor | NORMAL | 2025-02-11T19:13:20.939053+00:00 | 2025-02-11T19:13:20.939053+00:00 | 63 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
if X is the minimum in the game score array, then we need to make sure everyone should have atleast this value
Then we can say if we can acheive this with m moves
given a score, determine how many visits are required to acheive this score basically ceil(score/point)
optimal movement is forward->backward->forward->backward....,
need 2*visites to make the score
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(log(1e15)*N)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(N)
# Code
```cpp []
#define ll long long
#define vi vector<ll>
class Solution {
public:
long long maxScore(vector<int>& points, ll m) {
ll n = points.size();
ll low = 1;
ll high = 1e15;
ll ans = 0;
std::function<bool(ll)> ispos = [&](ll score) -> bool {
vi game_visit(n+1, 0);
for(ll i = 0; i<n; i++){
game_visit[i] = ((score + 1ll*points[i] -1ll)/points[i]);
}
//we need to visit this cell this many amount of times
ll moves = 0;
ll ind = 0;
while(ind < n){
if((ind == n-1) && (game_visit[ind] <= 0)){
//last cell case
break;
}
moves++;
game_visit[ind]--; //from previous, come here
if(moves > m) break;
if(game_visit[ind] <= 0){
//from previous come here
ind++;
continue;
}
game_visit[ind+1] -= (game_visit[ind]);
moves += (2ll*game_visit[ind]);
game_visit[ind] = 0;
ind++;
}
if(moves <= m) return true;
else return false;
};
while(low <= high){
ll mid = (low + high)/2;
if(ispos(mid)){
ans = mid;
low = mid+1;
}
else{
high = mid-1;
}
}
return ans;
}
};
``` | 1 | 0 | ['Binary Search', 'Greedy', 'C++'] | 0 |
maximize-the-minimum-game-score | Java Solution using BS | java-solution-using-bs-by-shaurya_malhan-9amd | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Shaurya_Malhan | NORMAL | 2025-02-10T14:30:22.697183+00:00 | 2025-02-10T14:30:22.697183+00:00 | 12 | 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
```java []
class Solution {
public long maxScore(int[] p, int m) {
int n = p.length;
long start = 0;
long end = (long) 1e17;
while(start < end) {
long mid = start + (end - start) / 2;
int i = 0;
long sum = 0;
long prev = 0;
while(i < n) {
if(i == n - 1) {
long l = p[i];
long u = ((mid + l - 1) / l) - prev;
sum += (2 * u) - 1;
break;
}
long l = p[i];
long r = p[i + 1];
long u = ((mid + l - 1) / l) - prev;
long v = ((mid + r - 1) / r);
long max = Math.max(u, v);
if(max == u) {
if(i == n - 2 && u > v) {
sum += 2 * max - 1;
break;
}
sum += 2 * max;
prev = 0;
i += 2;
} else {
sum += 2 * u - 1;
prev = u - 1;
i++;
}
}
if (sum > m) {
end = mid;
} else {
start = mid + 1;
}
}
return start - 1;
}
}
``` | 1 | 0 | ['Java'] | 0 |
maximize-the-minimum-game-score | Biary search on answer | biary-search-on-answer-by-user2479gs-8pbn | Code | user2479GS | NORMAL | 2025-02-09T09:49:58.854710+00:00 | 2025-02-09T09:49:58.854710+00:00 | 121 | false |
# Code
```cpp []
class Solution {
public:
bool poss(vector<long long> &p, long long mid, long long m)
{
vector<long long> v(p.size(), 0);
for (int i = 0; i < p.size(); i++)
{
if (i==p.size()-1 && v[i] >= mid)
{
continue;
}
if (m > 0)
{
v[i]+= p[i];
m--;
}
else
{
return false;
}
long long d = v[i];
if (v[i] >= mid)
{
continue;
}
else
{
long long rem = mid - d;
long long move = rem / p[i];
// cout << rem << " " << move << endl;
if (rem % p[i] != 0)
{
move++;
}
long long move1 = move;
move1 *= 2;
if (m >= move1)
{
m -= move1;
if (i + 1 < p.size())
{
long long temp = p[i + 1];
temp *= move;
v[i + 1] = temp;
}
}
else
{
// cout << "f1" << endl;
return false;
}
}
}
return true;
}
long long maxScore(vector<int> &p, int m)
{
long long m1 = m;
int n = p.size();
vector<long long> v(n);
for (int i = 0; i < n; i++)
{
v[i] = p[i];
}
long long s = 1;
long long e = 1e15;
long long ans = 0;
// cout << poss(v, 4, m1) << endl;
while (s <= e)
{
long long mid = s + (e - s) / 2;
if (poss(v, mid, m1))
{
ans = mid;
s = mid + 1;
}
else
{
e = mid - 1;
}
}
return ans;
}
};
``` | 1 | 0 | ['C++'] | 0 |
maximize-the-minimum-game-score | Easy Python Solution || Simple Explanation Given || | easy-python-solution-simple-explanation-s34kz | IntuitionThe code uses binary search to find the highest minimum game score achievable with at most m moves.For each candidate score, the helper function simula | Abhyanand_Sharma | NORMAL | 2025-02-09T04:42:14.977620+00:00 | 2025-02-09T04:42:14.977620+00:00 | 128 | false | # Intuition
The code uses binary search to find the highest minimum game score achievable with at most m moves.
For each candidate score, the helper function simulates moving through the points array, "boosting" the score when needed by spending extra moves.
It returns the maximum candidate score for which the simulation confirms that every game index can reach that score under the move constraints.<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
### **Approach in 7 Steps** 🚀
1️⃣ **Initialize Variables** 📌 – Define "low = 0" and "high = min(points) * m", setting the binary search range for the maximum achievable minimum score.
2️⃣ **Binary Search Begins** 🔍 – Use a binary search loop to find the highest possible score that can be maintained across the array.
3️⃣ **Simulate the Game** 🎮 – For each mid-score candidate, the "possible()" function checks whether the score can be achieved with at most "m" moves.
4️⃣ **Iterate Through Points** 🔄 – Traverse "points[]", trying to maintain the candidate score while tracking how many moves are needed.
5️⃣ **Boost Scores If Needed** ⚡ – If the score at an index is too low, calculate the number of moves needed to boost it and adjust remaining moves accordingly.
6️⃣ **Early Termination Check** 🚨 – If at any point the remaining moves are insufficient, return "False" to indicate the candidate score is unachievable.
7️⃣ **Update Search Range & Return Answer** ✅ – If the score is possible, increase "low"; otherwise, decrease "high". The final "low" value is the answer.
This **efficiently finds the highest achievable minimum score using binary search + simulation**! 🚀🔥<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
O(n log m) (Binary search + simulation)<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
O(1) (Constant extra space)<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def maxScore(self, points: List[int], m: int) -> int:
n = len(points)
pts = points # local alias to reduce attribute lookup overhead
if m < n:
return 0
def possible(count, moves):
score = pts[0]
moves -= 1 # first move used to get to index 0
# Iterate over each index
for i in range(n):
nextScore = 0
# If current score is too low, perform extra oscillations.
if score < count:
diff = count - score
# Replace math.ceil(diff / pts[i]) with integer math.
required_moves = (diff + pts[i] - 1) // pts[i]
if moves < 2 * required_moves:
return False
moves -= 2 * required_moves
if i + 1 < n:
nextScore += pts[i + 1] * required_moves
if i + 1 < n:
# If no moves remain and nextScore is too low, fail early.
if moves <= 0 and nextScore < count:
return False
moves -= 1 # cost for moving forward
nextScore += pts[i + 1]
score = nextScore
return True
low, high = 0, min(pts) * m
while low < high:
mid = (low + high + 1) // 2
if possible(mid, m):
low = mid
else:
high = mid - 1
return low
``` | 1 | 0 | ['Binary Search', 'Dynamic Programming', 'Simulation', 'Python3'] | 0 |
maximize-the-minimum-game-score | simple solution Java , beats 98%. | simple-solution-java-beats-98-by-naveen_-x8om | Just another binary search on ans type question.
greedy part is moving to and fro until we get min req value for that index.Time complexity is n*log(max(points[ | naveen_gunnam | NORMAL | 2025-03-02T02:07:14.224308+00:00 | 2025-03-02T02:07:14.224308+00:00 | 7 | false | Just another binary search on ans type question.
greedy part is moving to and fro until we get min req value for that index.
Time complexity is n*log(max(points[i])*m) =~ 10^4 * 50 .
and Space complexity O(1)
Happy Hacking :)
# Code
```java []
class Solution {
public long maxScore(int[] points, int m) {
long i = 1 , j = (long)1e15;
long maxFound = 0;
while(i<=j){
long mid = i+(j-i)/2;
if(find(points,m,mid)){
maxFound = mid;
i = mid+1;
}else{
j = mid-1;
}
}
return maxFound;
}
boolean find(int[] points , long m , long min){
int i = 0;
long curr=0;
while(i<points.length-1 && m>=0){
long currReq = min-curr;
if(currReq<=points[i]){ // just move ahead
m--;
i++;
curr=0;
continue;
}
long minVisitsRequired = (currReq+points[i]-1)/points[i]; // the below commented line of code can be replaced by this.
// long minVisitsRequired = currReq%points[i]==0?currReq/points[i]:(currReq/points[i])+1;
long movesRequiredToMakeMinVists = 2*(minVisitsRequired)-1;
curr = (minVisitsRequired-1)*points[i+1];
m -= movesRequiredToMakeMinVists;
i++;
}
if(i==points.length-1 && curr<min) m-= 2*((min-curr+points[i]-1)/points[i])-1; // last index edge case
return m>=0;
}
}
/*
m = 5
1 2 3
0 0 0
2 4 3
m = 10
0 1 2 3 4 5
1 4 6 1 5 2
1 4
1 4 6 1 5
1 5 2
1(9)
4(8)
1(7) 6(7)
4(6) 4(6) 1(6)
1(5) 6(5)
4(4) 4(4) 1(4)
1(3) 6(3)
4(2)
1(1)
4(0)
ha after hints
lets try binary search on answer
max possible (m/2+1)*min
min 1
=~ n*log(m*min) total TC
0 1 3
1 2 3
1 2
1 2
1 2
1
3 4 0
13
3
1 2
3 4
5 6
7
5 25 15
5 25
5 25
5 25
7 2
4 3
28 6
15
*/
``` | 0 | 0 | ['Java'] | 0 |
maximize-the-minimum-game-score | [C++] Binary seach, short code with comments | c-binary-seach-short-code-with-comments-fyt8z | IntuitionA fixed number X can be the minimum of the gamescore array iff the minimum amount of operations required to bring every element in the game score array | andititu_ | NORMAL | 2025-02-25T22:25:28.911250+00:00 | 2025-02-25T22:25:28.911250+00:00 | 5 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
A fixed number X can be the minimum of the gamescore array iff the minimum amount of operations required to bring every element in the game score array to that X is less than m. To determine the minimum amount of operations to bring every element of a gamescore array to X, a greedy approach is taken: if every element in the array is bigger or equal than X, then the amount of operations we are looking for is the length of the array itself. If one element is smaller than X, then the fastest way to make it greater than X is to go back and front between this element and the next in the array performing the operations defined by the problem.
You could perform a linear search for X in this way, but the time limit forces us to use a faster search, like BS.
# Complexity
- Time complexity: $$O(N*log(10^{18}))$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(1)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
long long maxScore(vector<int>& points, int m) {
int n = points.size();
if(m < n) return 0;
long long res = 0;
long long lo = 1;
long long hi = 1e18;
while(lo <= hi) {
// target x
long long x = lo + (hi - lo)/ 2;
// keep track of total operations needed for X
long long ops = 0;
// while making an index i satisy the requirement, you're inadvertently affecting the amount of operations required for index i+1 to satisfy the requirement, so keep track of that.
long long carryOver = 0;
for(int i = 0; i < n && ops <= m; ++i) {
long long k = points[i];
// g is the amount of times the element must be added to itself so it's greater than the target X.
long long g = (x%k == 0) ? x/k : x/k + 1;
// this amount is reduced by the carry over
g -= carryOver;
// if we're at the last element, but no further increase is needed then we can stop
if(i == n-1 && g <= 0)break;
// substract one due to the way we count operations
g--;
g = max(0LL, g);
// count operations
ops += 1 + 2*g;
// record next carry over
carryOver = g;
}
// Binary search bounds update
if(ops <= m) {
res = x;
lo = x + 1;
} else {
hi = x - 1;
}
}
return res;
}
};
``` | 0 | 0 | ['C++'] | 0 |
maximize-the-minimum-game-score | binary search on answer approach. | binary-search-on-answer-approach-by-anur-vfti | IntuitionWe need to maximize the minimum score in the gameScore array after making at most m moves. Since each move increases a game’s score by a fixed amount ( | anurag_bandejiya | NORMAL | 2025-02-15T12:53:48.039250+00:00 | 2025-02-15T12:53:48.039250+00:00 | 14 | false | # Intuition
We need to maximize the minimum score in the gameScore array after making at most m moves. Since each move increases a game’s score by a fixed amount (the corresponding value from points), we can rephrase the problem as: "What is the highest minimum score we can guarantee across all games using at most m moves?"
A natural idea is to use binary search over the candidate minimum scores. For each candidate value, we simulate the process to determine how many moves are required to boost every game’s score to at least that value. If we can achieve that within m moves, then the candidate is feasible.
# Approach
1.Binary Search on Candidate Minimum Score:
We set the search space from a lower bound of 0 up to a high bound (for example, e15). For each candidate minimum score (let’s call it minScoreCandidate), we check if it's possible to achieve that minimum value across all games using at most m moves.
2.Simulation via the check Function:
For each game (indexed by i), we calculate the number of times we need to add points[i] to reach minScoreCandidate.
The required number of visits is essentially:
ceil ( minScoreCandidate / points[𝑖] ) .
The first visit costs 1 move, and each additional visit costs 2 moves (because you must move back and forth to revisit that index).
We also use accumulators (named carryVisits and bonusMoves in our code) to model how extra visits from previous games can reduce the overall move cost.
If the total moves required across all games is within the allowed m moves, the candidate is feasible; otherwise, it is not.
3.Adjusting the Search:
Based on the simulation result, we adjust our binary search range. If the candidate is achievable, we try for a higher minimum; if not, we lower the candidate.
# 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:
#define ll long long
// Helper function: returns true if it's possible to achieve a minimum gameScore
// of 'minScoreCandidate' using at most 'maxMoves' moves.
bool canAchieveMinScore(vector<int>& points, ll maxMoves, ll minScoreCandidate) {
int n = points.size();
ll totalMovesUsed = 0; // total moves needed so far
ll carryVisits = 0; // extra visits carried over to this game
ll bonusMoves = 0; // bonus moves from previous games
for (int i = 0; i < n; i++) {
// Calculate the required visits for the i-th game to reach minScoreCandidate.
ll requiredVisits = (minScoreCandidate + points[i] - 1) / points[i]; // ceil(minScoreCandidate/points[i])
if (carryVisits >= requiredVisits) {
// If we have enough carry visits, no extra moves are needed;
// reset carry and accumulate bonus moves.
carryVisits = 0;
bonusMoves++;
} else {
// Calculate the current score contributed by the carried visits.
ll currentScore = points[i] * carryVisits;
// Determine how many additional visits are needed for this game.
ll remainingScoreNeeded = minScoreCandidate - currentScore;
requiredVisits = (remainingScoreNeeded + points[i] - 1) / points[i];
// Each additional visit (after the first) requires 2 moves (one forward, one backward),
// and the first additional visit requires 1 move.
totalMovesUsed += requiredVisits * 2 - 1;
if(totalMovesUsed > maxMoves)
return false;
// Update the carry: after making 'requiredVisits' moves, we can use (requiredVisits - 1) moves for the next game.
carryVisits = max(requiredVisits - 1, 0LL);
totalMovesUsed += bonusMoves; // add any bonus moves from previous games
if(totalMovesUsed > maxMoves)
return false;
bonusMoves = 0;
}
}
return totalMovesUsed <= maxMoves;
}
long long maxScore(vector<int>& points, int m) {
int n = points.size();
ll low = 0;
ll high = 1e15; // high bound for binary search on candidate minimum gameScore
ll minPoint = *min_element(points.begin(), points.end());
ll ans = high;
// Binary search for the maximum achievable minimum score.
while (low <= high) {
ll mid = low + (high - low) / 2;
if (canAchieveMinScore(points, m, mid)) {
ans = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
// If the number of moves equals the number of games, return the max between the found answer and the minimum point.
if (m == n) {
return max(ans, minPoint);
}
return ans;
}
};
``` | 0 | 0 | ['Binary Search', 'Greedy', 'C++'] | 0 |
maximize-the-minimum-game-score | Binary search | C++ | binary-search-c-by-siddharth96shukla-6h1x | Complexity
Time complexity: O(n∗log(1e15))
Code | siddharth96shukla | NORMAL | 2025-02-14T13:47:00.219619+00:00 | 2025-02-14T13:47:00.219619+00:00 | 13 | false | # Complexity
- Time complexity: $$O(n*log(1e15))$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
#define ll long long int
class Solution {
public:
bool chk(ll val, int m, vector<int>&A){
int n=A.size(), skip=0;
ll necessary=0, transfer=0, total=0, p;
for(int i=0;i<n && total<=m;i++){
p = A[i];
necessary = ceil(val/(1.0*p));
if(necessary<=transfer){
skip++;
transfer=0;
}
else{
ll x = ceil((val - transfer*p)/(1.0*p));
total+=(2*x - 1);
total+=skip;
transfer = max((ll)0, x-1);
skip=0;
}
}
return (total<=m);
}
long long maxScore(vector<int>& A, int mx) {
ll l=0, r=1e15, m;
while(r-l > 1){
m = l+((r-l)>>1);
if(chk(m, mx, A))l=m;
else r=m;
}
return l;
}
};
``` | 0 | 0 | ['Binary Search', 'C++'] | 0 |
maximize-the-minimum-game-score | Maximize the Minimum Game Score | maximize-the-minimum-game-score-by-jeyap-a27k | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | jeyapragash1 | NORMAL | 2025-02-13T07:51:20.482808+00:00 | 2025-02-13T07:51:20.482808+00:00 | 12 | 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
```java []
import java.util.*;
public class Solution {
public long maxScore(int[] points, int m) {
int n = points.length;
// Lower bound is 0; an upper bound is:
// In the best case you might get about (1 + (m-1)/2) visits at a game,
// so the maximum score for any game is at most points[i]*(1+(m-1)/2).
// Hence the overall maximum possible minimum score is no more than
// min(points) * (1 + (m-1)/2).
long minPoint = Long.MAX_VALUE;
for (int p : points) {
if(p < minPoint) minPoint = p;
}
long hi = minPoint * (1 + (m - 1L) / 2);
long lo = 0, ans = 0;
while (lo <= hi) {
long mid = lo + (hi - lo) / 2;
if(feasible(mid, points, m)) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private boolean feasible(long X, int[] points, long m) {
int n = points.length;
if(X == 0) return true; // always feasible
long[] R = new long[n];
for (int i = 0; i < n; i++){
// Compute R[i] = ceil(X/points[i])
R[i] = (X + points[i] - 1) / points[i];
if(R[i] < 1) R[i] = 1;
}
int N = n - 1; // number of "edges" (k–variables)
// Pattern A:
long[] kA = new long[N];
if(N > 0) {
long A0 = R[0] - 1; // needed extra at game 0
kA[0] = A0;
for (int i = 1; i < N; i++) {
long req = R[i] - 1; // constraint for game i, 1<= i <= n-2
kA[i] = Math.max(req - kA[i - 1], 0);
}
// Finally, game n-1 must satisfy: 1 + kA[N-1] >= R[n-1]
long lastReq = R[n - 1] - 1;
if(kA[N - 1] < lastReq) {
kA[N - 1] = lastReq;
}
}
long S_A = 0;
for (int i = 0; i < N; i++) {
S_A += kA[i];
}
long costA = n + 2 * S_A;
// Pattern B:
long[] kB = new long[N];
if(N > 0) {
long A0 = R[0] - 1;
kB[0] = A0;
for (int i = 1; i < N; i++) {
long req = R[i] - 1;
kB[i] = Math.max(req - kB[i - 1], 0);
}
// For Pattern B, game n-1 must satisfy: v[n-1] = kB[N-1] >= R[n-1].
long lastReqB = R[n - 1];
if(kB[N - 1] < lastReqB) {
kB[N - 1] = lastReqB;
}
}
long S_B = 0;
for (int i = 0; i < N; i++) {
S_B += kB[i];
}
long costB = (n - 1) + 2 * S_B;
long minCost = Math.min(costA, costB);
return minCost <= m;
}
}
``` | 0 | 0 | ['Java'] | 0 |
maximize-the-minimum-game-score | 3449. Maximize the Minimum Game Score | 3449-maximize-the-minimum-game-score-by-wyhb1 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | jeyapragash1 | NORMAL | 2025-02-13T07:33:39.082083+00:00 | 2025-02-13T07:33:39.082083+00:00 | 6 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
import java.util.*;
public class Solution {
public long maxScore(int[] points, int m) {
int n = points.length;
// Lower bound is 0; an upper bound is:
// In the best case you might get about (1 + (m-1)/2) visits at a game,
// so the maximum score for any game is at most points[i]*(1+(m-1)/2).
// Hence the overall maximum possible minimum score is no more than
// min(points) * (1 + (m-1)/2).
long minPoint = Long.MAX_VALUE;
for (int p : points) {
if(p < minPoint) minPoint = p;
}
long hi = minPoint * (1 + (m - 1L) / 2);
long lo = 0, ans = 0;
while (lo <= hi) {
long mid = lo + (hi - lo) / 2;
if(feasible(mid, points, m)) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private boolean feasible(long X, int[] points, long m) {
int n = points.length;
if(X == 0) return true; // always feasible
long[] R = new long[n];
for (int i = 0; i < n; i++){
// Compute R[i] = ceil(X/points[i])
R[i] = (X + points[i] - 1) / points[i];
if(R[i] < 1) R[i] = 1;
}
int N = n - 1; // number of "edges" (k–variables)
// Pattern A:
long[] kA = new long[N];
if(N > 0) {
long A0 = R[0] - 1; // needed extra at game 0
kA[0] = A0;
for (int i = 1; i < N; i++) {
long req = R[i] - 1; // constraint for game i, 1<= i <= n-2
kA[i] = Math.max(req - kA[i - 1], 0);
}
// Finally, game n-1 must satisfy: 1 + kA[N-1] >= R[n-1]
long lastReq = R[n - 1] - 1;
if(kA[N - 1] < lastReq) {
kA[N - 1] = lastReq;
}
}
long S_A = 0;
for (int i = 0; i < N; i++) {
S_A += kA[i];
}
long costA = n + 2 * S_A;
// Pattern B:
long[] kB = new long[N];
if(N > 0) {
long A0 = R[0] - 1;
kB[0] = A0;
for (int i = 1; i < N; i++) {
long req = R[i] - 1;
kB[i] = Math.max(req - kB[i - 1], 0);
}
// For Pattern B, game n-1 must satisfy: v[n-1] = kB[N-1] >= R[n-1].
long lastReqB = R[n - 1];
if(kB[N - 1] < lastReqB) {
kB[N - 1] = lastReqB;
}
}
long S_B = 0;
for (int i = 0; i < N; i++) {
S_B += kB[i];
}
long costB = (n - 1) + 2 * S_B;
long minCost = Math.min(costA, costB);
return minCost <= m;
}
}
``` | 0 | 0 | ['Java'] | 0 |
maximize-the-minimum-game-score | Maximize the Minimum Game Score (Beats 100% ) TC:- O(N), SC:- O(1) | maximize-the-minimum-game-score-beats-10-3x20 | Complexity
Time complexity: O(Log(Max(points)))
Space complexity: O(1)
Code | Ansh1707 | NORMAL | 2025-02-12T21:17:48.397173+00:00 | 2025-02-12T21:17:48.397173+00:00 | 14 | false |
# Complexity
- Time complexity: O(Log(Max(points)))
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python []
class Solution(object):
def is_possible(self, target_time, points, max_moves):
moves_used = extra_time = bonus = 0
for point in points:
required_moves = -(-target_time // point)
if extra_time >= required_moves:
extra_time, bonus = 0, bonus + 1
else:
deficit = required_moves - extra_time
moves_used += 2 * deficit - 1 + bonus
extra_time, bonus = deficit - 1, 0
if moves_used > max_moves:
return False
return True
def maxScore(self, points, max_moves):
"""
:type points: List[int]
:type max_moves: int
:rtype: int
"""
if max_moves < len(points):
return 0
left, right, result = 1, 10**18, 0
while left <= right:
mid = left + (right - left) // 2
if self.is_possible(mid, points, max_moves):
result, left = mid, mid + 1
else:
right = mid - 1
return result
``` | 0 | 0 | ['Binary Search', 'Greedy', 'Python'] | 0 |
maximize-the-minimum-game-score | BS + Greedy | CPP Solution | bs-greedy-cpp-solution-by-cholebhature-mttt | Complexity
Time complexity:
O(nlog(max(points)∗m)) (i have approximated it to be 10^15 in the solution)
Space complexity:
O(1)
Code | cholebhature | NORMAL | 2025-02-12T10:18:43.483715+00:00 | 2025-02-12T10:18:43.483715+00:00 | 21 | false | # Complexity
- Time complexity:
$$O(nlog(max(points)*m))$$ (i have approximated it to be 10^15 in the solution)
- Space complexity:
$$O(1)$$
# Code
```cpp []
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
bool f(const vector<int>& points, long long m, long long x) {
long long n = points.size();
long long rem = m;
long long nxt = 0;
for (long long i = 0; i < n; ++i) {
if (i == n - 1) {
if (x-(points[i]*nxt)<=0)
return 1;
long long need = (x - (points[i] * nxt)) / points[i] + ((x - (points[i] * nxt)) % points[i] != 0);
return 2 * need - 1 <= rem;
}
if (x - (points[i] * nxt) <= 0) {
nxt = 0;
rem -= 1;
if (rem < 0) {
return false;
}
continue;
}
long long need = (x - (points[i] * nxt)) / points[i] + ((x - (points[i] * nxt)) % points[i] != 0);
need = max(need, 0LL);
rem -= max(0LL, 1LL + (2LL * (need - 1)));
nxt = max(0LL, need - 1);
if (rem < 0) {
return false;
}
}
return true;
}
long long maxScore(vector<int>& points, long long m) {
long long left = 1, right = 1e15;
while (left <= right) {
long long mid = left + (right - left) / 2;
if (f(points, m, mid)) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left - 1;
}
};
``` | 0 | 0 | ['C++'] | 0 |
maximize-the-minimum-game-score | Easy Implementation !!!! | easy-implementation-by-adsulswapnil27-nuvy | IntuitionApproachComplexity
Time complexity: O(n*log(n))
Space complexity: O(1)
Code | adsulswapnil27 | NORMAL | 2025-02-11T13:53:20.270110+00:00 | 2025-02-11T13:53:20.270110+00:00 | 25 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: O(n*log(n))
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
long long maxScore(vector<int>& arr, int m) {
long long l=0,r=1e15;
int n = arr.size();
long long q=0;
while(l<=r){
long long mid = (l+r)/2;
long long next = 0;
long long ans = 0;
for(int i=0;i<n;i++){
long long h= arr[i];
if(next>1e10){
ans+=next;
break;
}
long long sum = (next*h) ;
long long tar = max((long long)0, mid - sum);
long long req = max((long long)1,(tar+arr[i]-1)/arr[i]);
next=req-1;
if(i==n-1){
if((tar+arr[i]-1)/arr[i] != 0) ans += req+req-1;
}
else
ans+=req+req-1;
}
if( m < ans){
q=mid;
r = mid-1;
}
else {
l = mid+1;
}
}
if(l==0)return 0;
return l-1;
}
};
``` | 0 | 0 | ['Binary Search', 'C++'] | 0 |
maximize-the-minimum-game-score | Binary Search Solution With Comments. | binary-search-solution-with-comments-by-kh2gp | Code | vaibhavkhanna8bp | NORMAL | 2025-02-11T13:42:49.767647+00:00 | 2025-02-11T13:45:04.421737+00:00 | 16 | false | # Code
```java []
class Solution {
// In this function, I have used the methodology that how many steps will be taken in total
// for currentIndex, that is i to fulfill its quota, that also includes moving to ith index,
// After every iteration calculation is done so that how many moves were required to fulfill quota
// and move to i, in next iteration we will again count moves required for (i+1) which will always count
// 1 move for moving to (i+1). This is because we are starting to move from -1 initially, even moving to 0
// index required 1 step.
private boolean canCurrentScoreBeAchievedAtAllIndices(int[] points, long targetScore, int m) {
long previousPointsAccumulated = 0;
long totalMovesTaken = 0;
for (int i = 0; i < points.length; i++) {
long minimumPointsNeededForCurrentIndex = targetScore - previousPointsAccumulated;
// Check, if No Additional Moves Required For Current Index
// Assign previousPointsAccumulated to 0 for next iteration
// and increment totalMovesTaken by 1 to accommodate moving to ith index.
if (minimumPointsNeededForCurrentIndex <= 0) {
// If last index quota's is already filled, we will not even move to that index.
// What will we do there ? Time pass ?
if (i == points.length - 1) {
return true;
} else {
totalMovesTaken++;
if (totalMovesTaken > m) {
return false;
}
previousPointsAccumulated = 0;
continue;
}
}
// long minimumMovesToAccumulateMinimumPoints = (long) Math.ceil((double) minimumPointsNeededForCurrentIndex / points[i]);
// For Overflow substituting above value to below value
long minimumMovesToAccumulateMinimumPoints = (minimumPointsNeededForCurrentIndex + points[i] - 1) / points[i];
totalMovesTaken += (2 * minimumMovesToAccumulateMinimumPoints - 1);
if (totalMovesTaken > m) {
return false;
}
if (i != points.length - 1) {
previousPointsAccumulated = (minimumMovesToAccumulateMinimumPoints - 1) * (points[i + 1]);
}
}
return true;
}
public long maxScore(int[] points, int m) {
long left = 0;
long right = ((long) (m + 1) * points[0]) / 2;
long answer = 0;
while (left <= right) {
long mid = (left + right) / 2;
if (canCurrentScoreBeAchievedAtAllIndices(points, mid, m)) {
answer = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}
return answer;
}
}
``` | 0 | 0 | ['Java'] | 0 |
maximize-the-minimum-game-score | greedy + binarySearch by coderkb | greedy-binarysearch-by-coderkb-by-coderk-429g | IntuitionWe need to maximize the minimum game score by distributing at most m game moves. The score of a position increases by its respective points[i] value pe | coderkb | NORMAL | 2025-02-11T02:48:44.388297+00:00 | 2025-02-11T02:48:44.388297+00:00 | 21 | false | ### Intuition
We need to **maximize the minimum game score** by distributing at most `m` game moves. The score of a position increases by its respective `points[i]` value per move.
Since we're maximizing a **minimum value**, we can use **binary search** on the possible score range. The idea is to check whether a given score (`target`) is **achievable** within `m` moves. If it is, we try for a higher score.
---
### Approach
#### 1. **Binary Search on the Minimum Score**
- We perform a **binary search** on the minimum possible score (`low`) to the highest possible score (`high`).
- `low = 1` (minimum score is at least `1`).
- `high = ((m + 1) / 2) * points[0]` (since in the worst case, the first element will be incremented as much as possible).
#### 2. **Checking Feasibility (`isPossible` function)**
- We iterate over the `points` array to check if we can **reach** the `target` score using at most `m` moves.
- If we can achieve the `target`, we **increase the search range**.
- Otherwise, we **reduce the search range**.
#### 3. **Finding the Maximum Achievable Score**
- We update `ans` every time a valid `target` is found and continue searching for a higher one.
---
### Complexity Analysis
- **Binary Search Range**: The maximum value is `O(m * points[0])`, so the number of iterations is **O(log(m * points[0]))**.
- **Feasibility Check (`isPossible`)**: It runs in **O(n)**.
- **Overall Complexity**: **O(n log(m * points[0]))**.
---
### Code with Comments
```java
class Solution {
// Function to check if a given target score is possible with at most 'm' moves
boolean isPossible(int[] points, int m, long target, int n) {
long[] gameScore = new long[points.length]; // Store scores at each position
long currMoves = 0; // Track number of moves used
for (int i = 0; i < n && currMoves <= m; ++i) {
long req = target - gameScore[i]; // Additional score needed at position i
if (req <= 0) { // If already at or above target
if (i != n - 1) ++currMoves;
continue;
}
long k = (req + points[i] - 1) / points[i]; // Number of moves required at i
currMoves += (2 * k - 1); // Each move affects two positions
if (i != n - 1) {
gameScore[i + 1] = points[i + 1] * (k - 1); // Carry extra moves to next index
}
}
return currMoves <= m; // Check if moves used are within limit
}
public long maxScore(int[] points, int m) {
long low = 1, high = 1L * (m + 1) / 2 * points[0], ans = 0;
int n = points.length;
while (low <= high) {
long mid = low + (high - low) / 2;
if (isPossible(points, m, mid, n)) { // If 'mid' score is achievable
ans = mid; // Update the answer
low = mid + 1; // Try for a higher score
} else {
high = mid - 1; // Try for a lower score
}
}
return ans; // Maximum achievable score
}
}
``` | 0 | 0 | ['Binary Search', 'Greedy', 'Java'] | 0 |
maximize-the-minimum-game-score | Explained | 190ms | ranges::lower_bound views::iota | explained-190ms-rangeslower_bound-viewsi-2ixd | IntuitionMaximize the minimum game score by strategically distributing limited moves across array elements, using binary search to find the optimal minimum scor | ivangnilomedov | NORMAL | 2025-02-10T19:38:22.906598+00:00 | 2025-02-10T19:38:22.906598+00:00 | 14 | false | # Intuition
Maximize the minimum game score by strategically distributing limited moves across array elements, using binary search to find the optimal minimum score.
# Approach
1. **Binary Search on Answer**
- Instead of brute-forcing all possible move distributions, we search for the maximum achievable minimum score
- Use reverse binary search to find the highest possible minimum score
2. **Move Distribution Strategy**
- Simulate score incrementation across array elements
- Track "inherited" moves from previous cells
- Ensure each cell reaches target minimum score with limited total moves
3. **Key Optimization Techniques**
- Dynamically calculate required increments for each cell
- Handle last cell specially
# Complexity
- Time complexity: $$O(N \log(\text{MAX\_SCORE}))$$
# Code
```cpp []
#include <algorithm>
#include <ranges>
class Solution {
public:
long long maxScore(const vector<int>& points, const int M) {
long long max_ans = static_cast<long long>(M) * ranges::max(points) / points.size() + 1;
// Binary search the maximum possible minimum score
return *ranges::lower_bound(
// Find the firts i.e. bigest (because reverse) score where total_moves_count <= M
ranges::views::iota(1LL, max_ans + 1) | views::reverse,
static_cast<long long>(M),
[&points](long long score, long long M) { // Check if a given minimum score is achievable
// While incrementing a cell it can not be incremented alone, this is count of increments
// the cell inherits from the one to the left
long long inherit_incs = 1;
long long total_moves_count = 0;
for (int i = 0; i < points.size() && total_moves_count <= M; ++i) { // Simulate score distribution
long long need_increments = max(0LL, score - 1) / points[i] + 1;
if (i == points.size() - 1 && need_increments < inherit_incs)
// Special case for last cell: potentially reduce inherited increments
--inherit_incs;
// Additional increments needed beyond inherited
long long need_more_incs = max(0LL, need_increments - inherit_incs);
total_moves_count += inherit_incs + need_more_incs;
// Inheritance for next cell
inherit_incs = need_more_incs + (i < points.size() - 1);
}
// Add final inherited increments
total_moves_count += inherit_incs;
return total_moves_count > M;
});
}
};
``` | 0 | 0 | ['C++'] | 0 |
maximize-the-minimum-game-score | JAVA SOLUTION (BINARY SEARCH) | java-solution-binary-search-by-divyansh_-o8kg | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | divyansh_2069 | NORMAL | 2025-02-10T17:21:55.160810+00:00 | 2025-02-10T17:21:55.160810+00:00 | 12 | 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
```java []
class Solution {
public long maxScore(int[] points, int m) {
int n=points.length;
int mini=Integer.MAX_VALUE;
int maxi=Integer.MIN_VALUE;
for(int num:points){
mini=Math.min(mini,num);
maxi=Math.max(maxi,num);
}
long low=0,high=(long)maxi*m;
long ans=0;
while(low<=high){
long mid=low+(high-low)/2;
if(solve(points,m,mid)){
ans=mid;
low=mid+1;
}
else{
high=mid-1;
}
}
return ans;
}
public boolean solve(int arr[],int m,long mid){
long count=0;
int n=arr.length;
long temp[]=new long[n];
for(int i=0;i<n-1;i++){
count++;
temp[i]+=arr[i];
long diff=mid-temp[i];
if(diff<=0) continue;
long steps=diff/(long)arr[i];
if(diff%arr[i]!=0) steps++;
temp[i]+=steps*arr[i];
temp[i+1]+=steps*arr[i+1];
count+=(2*steps);
}
if(temp[n-1]<mid){
count++;
temp[n-1]+=arr[n-1];
if(temp[n-1]<mid){
long diff=mid-temp[n-1];
long steps=diff/(long)arr[n-1];
if(diff%arr[n-1]!=0) steps++;
count+=(2*steps);
}
}
// System.out.println(mid+" "+count);
// System.out.println();
// System.out.println();
if(count<=(long)m) return true;
return false;
}
}
``` | 0 | 0 | ['Java'] | 0 |
maximize-the-minimum-game-score | Simple Binary Search | simple-binary-search-by-catchme999-r6jg | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | catchme999 | NORMAL | 2025-02-10T17:20:32.428526+00:00 | 2025-02-10T17:20:32.428526+00:00 | 29 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
from math import ceil
class Solution:
def maxScore(self, A: List[int], M: int) -> int:
N = len(A)
def possible(bound):
req = [ceil(bound/x) for x in A]
# print(req)
steps = 0
for i, x in enumerate(req):
if x:
steps += 2 * x - 1
if i + 1 < N:
req[i + 1] = max(0, req[i + 1] - (req[i] - 1))
elif i < N - 1:
steps += 1
return steps <= M
lo, hi = 0, int(10**6 * M / N) + 1
# possible(10)
ans=0
while lo <= hi:
mi=(lo+hi)//2
if possible(mi):
ans=mi
lo=mi+1
else:
hi = mi - 1
return ans
``` | 0 | 0 | ['Python3'] | 0 |
maximize-the-minimum-game-score | O(n*log(n) Binary search | onlogn-binary-search-by-luudanhhieu-yf1l | Intuition
Binary search log(n) and loop points -> O(n*log(n)) enough to pass this problem.
Try to every value from 0 -> max_int to check
How to loop points and | luudanhhieu | NORMAL | 2025-02-10T14:28:06.918558+00:00 | 2025-02-10T14:28:06.918558+00:00 | 13 | false | # Intuition
- Binary search log(n) and loop points -> O(n*log(n)) enough to pass this problem.
- Try to every value from 0 -> `max_int` to check
- How to loop points and check with value `vl` ?
- Start at `i = 0` and try to go to last of `points[i]` and ensure that `points[i]>= vl`
# Complexity
- Time complexity: O(n*log(n)
- Space complexity: O(1)
# Code
```golang []
func maxScore(points []int, m int) int64 {
if m < len(points) {
return 0
}
var start int64 = 1
var end int64 = 10000000000000000
mid := (start + end) / 2
for {
if start+1 >= end {
return start
}
if verify(points, mid, m) {
start = mid
} else {
end = mid
}
mid = (start + end) / 2
}
}
func verify(points []int, vl int64, m int) bool {
i0 := 0
var mv int64
var ml int64
for i0 < len(points) {
p0 := ml * int64(points[i0])
var rp int64 = 1
if (vl - p0) > 0 {
rp = (vl - p0) / int64(points[i0])
if vl%int64(points[i0]) != 0 {
rp++
}
mv += rp
ml = rp - 1
mv += ml
} else {
if i0 != len(points)-1 {
mv++
}
ml = 0
}
i0++
if mv > int64(m) {
return false
}
}
return true
}
``` | 0 | 0 | ['Go'] | 0 |
maximize-the-minimum-game-score | [Golang] Binary Search | golang-binary-search-by-silencerbupt-25kf | Given an integer bound, figure out the number of moves required to make gamescore[i] >= bound for all i. Use binary search to find the largest bound.Code | SilencerBUPT | NORMAL | 2025-02-10T13:58:54.151105+00:00 | 2025-02-10T13:58:54.151105+00:00 | 7 | false | Given an integer `bound`, figure out the number of moves required to make `gamescore[i] >= bound` for all `i`. Use binary search to find the largest `bound`.
# Code
```golang []
func maxScore(points []int, m int) int64 {
check := func(bound int) bool {
a, b := 0, 0
moves := 0
for i := 0; i < len(points)-1; i++ {
if a >= bound {
moves++
a, b = b, 0
if i+1 == len(points)-1 {
if a < bound {
k := (bound - a + points[i+1] - 1) / points[i+1]
moves += 2*k - 1
if moves > m {
return false
}
}
break
} else {
continue
}
}
k := (bound - a + points[i] - 1) / points[i]
a, b = b+points[i+1]*(k-1), 0
moves += 2*k - 1
if i+1 == len(points)-1 {
if a < bound {
k = (bound - a + points[i+1] - 1) / points[i+1]
moves += 2*k - 1
}
}
if moves > m {
return false
}
}
return true
}
l, r := 0, 500000000000001
for l < r {
t := (l + r) / 2
if check(t) {
l = t + 1
} else {
r = t
}
}
return int64(l - 1)
}
``` | 0 | 0 | ['Binary Search', 'Go'] | 0 |
maximize-the-minimum-game-score | My Solution | my-solution-by-hope_ma-0h2p | null | hope_ma | NORMAL | 2025-02-10T13:56:43.716213+00:00 | 2025-02-15T14:16:52.979261+00:00 | 16 | false | ```
/**
* the binary search solution is employed.
*
* Time Complexity: O(n * log(u))
* Space Complexity: O(1)
* where `n` is the length of the vector `points`
* `u` is (`m` * `min_point`)
* `min_point` is the minimum element of the vector `points`
*/
class Solution {
public:
long long maxScore(const vector<int> &points, const int m) {
const int n = static_cast<int>(points.size());
if (m < n) {
return 0;
}
long long low = 0;
const int min_point_index = static_cast<int>(min_element(points.begin(), points.end()) - points.begin());
long long high = static_cast<long long>(1 + ((m - n + (min_point_index == n - 2 ? 1 : 0)) >> 1)) * points[min_point_index] + 1;
while (low < high) {
const long long mid = low + ((high - low) >> 1);
if (can_achieve(points, mid, m)) {
low = mid + 1;
} else {
high = mid;
}
}
return high - 1;
}
private:
bool can_achieve(const vector<int> &points, const long long min_point, const int m) {
if (min_point == 0) {
return true;
}
const int n = static_cast<int>(points.size());
/**
* `remained_moves` stands for the remained moves that can be used
*/
int remained_moves = m;
/**
* `bonus_visits` stands for the times that a specific point has been
* visited when it's its turn to be visited.
*/
int bonus_visits = 0;
bool ret = true;
for (int i = 0; i < n; ++i) {
/**
* to make sure that the gameScore[i] is at least `min_point`,
* the point `points[i]` needs to be visited at least
* `ceil(min_point / points[i])` times
*/
int needed_visits = (min_point + points[i] - 1) / points[i] - bonus_visits;
if (i == n - 1 && needed_visits <= 0) {
/**
* at this time, gameScore[n - 1] is at least `min_point`,
* so no moves are needed
*/
break;
}
if (needed_visits < 1) {
/**
* all points but the point `points[n - 1]` need to be visited at least once
* in order to make the next points to be visited (to move forward)
*/
needed_visits = 1;
}
/**
* at this time, the point `points[i]` still needs to be visited `needed_visits`
* times, and the current position is (`i` - 1), the best strategy is as following,
* 1. move from points[i - 1] to points[i], and then
* 2. move from points[i] to points[i + 1], and then
* 3. move from points[i + 1] to points[i],
* etc..
*/
const int consumed_moves = (needed_visits << 1) - 1;
remained_moves -= consumed_moves;
if (remained_moves < 0) {
ret = false;
break;
}
/**
* in the process of moving described above, the point `points[i + 1]` has been visited
* (`needed_visits` - 1) times when the point `points[i]` is visited
*/
bonus_visits = needed_visits - 1;
}
return ret;
}
};
``` | 0 | 0 | ['C++'] | 0 |
maximize-the-minimum-game-score | Binary search/Greedy | binary-searchgreedy-by-jianstanleya-eg84 | IntuitionDidn't have time to do this contest in person, but it would have been nice. This question is the maximum-minimum type, which strongly suggests the use | jianstanleya | NORMAL | 2025-02-10T07:22:09.438338+00:00 | 2025-02-10T07:22:09.438338+00:00 | 18 | false | # Intuition
Didn't have time to do this contest in person, but it would have been nice. This question is the maximum-minimum type, which strongly suggests the use of binary search.
# Approach
We may ignore the specific values of points and consider the number of times each index is visited. Starting from the left, we must cover a certain range of indices. In order to minimize number of moves, we should jump between adjacent indices instead of moving across (it is either equivalent or worse).
As an analogy, suppose that you have to buy several items at a supermarket. The items are scattered around the store. Will you randomly run from one item to another or try to get items close to each other first?
# Complexity
- Time complexity: $O(N\log K)$, where $K$ is the range size of possible answers
- Space complexity: $O(N\log K)$
# Code
```cpp []
#define LL long long
class Solution {
public:
LL validate(LL mid, vector<int>& points) {
int n = points.size();
vector<LL> mult(n + 1);
for(int i = 0; i < n; ++i) mult[i] = mid / (LL)points[i] + (mid % (LL)points[i] == 0 ? 0 : 1);
int top = n - 1;
while(top >= 0 && mult[top] == 0) --top;
LL cost = 0;
for(int i = 0; i <= top; ++i) {
--mult[i];
++cost;
if(mult[i] > 0) {
cost += 2 * mult[i];
mult[i + 1] -= mult[i];
}
if(i + 1 == top && mult[i + 1] <= 0) break;
}
return cost;
}
LL maxScore(vector<int>& points, int m) {
LL lo = 0, hi = 1e16;
while(lo != hi) {
LL mid = lo + (hi - lo) / 2;
if(validate(mid, points) > m) hi = mid;
else lo = mid + 1;
}
return lo - 1;
}
};
``` | 0 | 0 | ['C++'] | 0 |
maximize-the-minimum-game-score | Simple Binary Search | simple-binary-search-by-bhaaratkhatri-iqbs | IntuitionWe will simply try to find minimum answer using binary search.ApproachWe will never decrease, we will always increase for every move.
For every index f | BhaaratKhatri | NORMAL | 2025-02-10T02:36:26.293939+00:00 | 2025-02-10T02:36:26.293939+00:00 | 25 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
We will simply try to find minimum answer using binary search.
# Approach
<!-- Describe your approach to solving the problem. -->
We will never decrease, we will always increase for every move.
1. For every index first we calculate how much moves are needed and we have to keep in mind that we can't stand at one position, we have to keep moving, so best approach is to oscillate between i and i+1.
2. Now we will traverse again and calculate needed moves (m) for index i.
3. When we achieved needed moves (m) for index i, at that point we will decrease moves (m - 1) from i + 1 as we have oscillate m-1 times at i + 1.
4. simply traverse and calculate solution.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(N * log(1e18))
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(N)
# Code
```cpp []
class Solution {
public:
long long maxScore(vector<int>& points, int m) {
long long left = 0, right = 1e18,n = points.size();
long long sol = 0;
//checker function
auto check = [&](long long mid) ->bool {
vector<long long> cnt(n,0);
for(int i = 0; i < n; i++) {
cnt[i] = (points[i] -1 + mid) / points[i];
}
long long moves = 0;
for(int i = 0; i < n; i++) {
if(cnt[i] <= 0 and i < n-1) moves++;
else {
long long req = 2 * (cnt[i] - 1);
moves += (req + 1);
if(i + 1 < n) cnt[i + 1] -= (cnt[i] - 1);
}
if(moves > m)
return false;
}
return true;
};
//normal bs
while(left <= right) {
long long mid = left + (right - left)/2;
if(check(mid)) {
sol = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}
return sol;
}
};
```
Thanks For Reading !! :-)
| 0 | 0 | ['C++'] | 0 |
maximize-the-minimum-game-score | [Python 3]Binary Search | python-3binary-search-by-chestnut890123-8mh5 | null | chestnut890123 | NORMAL | 2025-02-09T19:36:16.496601+00:00 | 2025-02-09T19:37:02.471424+00:00 | 21 | false |
```python3 []
class Solution:
def maxScore(self, points: List[int], m: int) -> int:
n = len(points)
def dp(target):
if not target:
return True
cnt = 0
prev_moves = 0
prev_idx = -1
i = 0
while i < n:
# already achieved in previous moves
if points[i] * prev_moves >= target:
prev_moves = 0
i += 1
continue
# need to move to i to achieve the target (no need for back-forth)
elif points[i] * (1 + prev_moves) >= target:
prev_moves = 0
cnt += i - prev_idx
prev_idx = i
i += 1
continue
# calculate the back-forth moves
diff = target - points[i] * (1 + prev_moves)
extra_moves = math.ceil(diff / points[i])
cnt += extra_moves * 2 + i - prev_idx
prev_moves = extra_moves
if cnt > m:
return False
prev_idx = i
i += 1
return cnt <= m
l, h = 0, max(points) * m
while l < h:
mid = l + (h - l + 1) // 2
if dp(mid):
l = mid
else:
h = mid - 1
return l
``` | 0 | 0 | ['Binary Search', 'Python3'] | 0 |
maximize-the-minimum-game-score | JAVA || Beats 100% || Binary Search | java-beats-100-binary-search-by-jai_hanu-73tf | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | jai_hanumant | NORMAL | 2025-02-09T19:25:16.266887+00:00 | 2025-02-09T19:25:16.266887+00:00 | 23 | 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
```java []
class Solution {
public long maxScore(int[] p, int m) {
int n=p.length;
long ans=0;
long l=0,h=(long)1e16;
while(l<=h){
long mid=(l+h)/2;
if(fun(mid,p,n,m)){
ans=mid;
l=mid+1;
}else{
h=mid-1;
}
}
return ans;
}
public static boolean fun(long mid, int p[],int n, int m){
long ans[]=new long[n];
for(int i=0;i<n;i++){
if(i==n-1 && ans[i]>=mid){
continue;
}
ans[i]+=p[i];
if(m<1)return false;
m--;
if(ans[i]<mid){
long time=(mid-ans[i]+p[i]-1)/p[i];
if(m<2*time){
return false;
}
if(i+1<n){
ans[i+1]+=p[i+1]*time;
}
m-=2*time;
}
}
return true;
}
}
``` | 0 | 0 | ['Java'] | 0 |
maximize-the-minimum-game-score | Maximize the Minimum Game Score [Beats 100% Speed & Storage] | maximize-the-minimum-game-score-beats-10-pn3h | Maximize the Minimum Game Score [Beats 100% Speed & Storage]IntuitionThe problem involves maximizing the minimum score in a game with limited moves. A binary se | hoanghung3011 | NORMAL | 2025-02-09T17:31:59.014657+00:00 | 2025-02-09T17:31:59.014657+00:00 | 57 | false | # Maximize the Minimum Game Score [Beats 100% Speed & Storage]
## Intuition
The problem involves maximizing the minimum score in a game with limited moves. A binary search approach is ideal because we can efficiently narrow down the maximum possible minimum score by checking feasibility for each candidate.
## Approach
1. **Binary Search**: Perform binary search on the possible values of the minimum score (`X`). The lower bound is `0`, and the upper bound is derived from the maximum achievable score based on the number of moves (`m`) and the points array.
2. **Feasibility Check**: For each midpoint (`X`), determine if it's possible to achieve a minimum score of `X` within the given number of moves (`m`).
3. **Two Patterns**:
- **Pattern A**: Always perform a forward move on every edge.
- **Pattern B**: Save one move on the final edge.
Use these patterns to calculate the minimal extra moves (`k`) required to meet the target score.
4. **Greedy Calculation**: Compute the total cost for both patterns and check if it fits within the allowed moves.
5. **Adjust Range**: Narrow the binary search range based on the feasibility result.
## Complexity
- **Time Complexity**: $$O(n \log k)$$, where `n` is the length of the `points` array and `k` is the range of possible scores.
- **Space Complexity**: $$O(n)$$, due to auxiliary arrays used for calculations.
## Tags
#BinarySearch #Greedy #Optimization #GameTheory #EfficientSolution
## Code
```java
import java.util.*;
public class Solution {
public long maxScore(int[] points, int m) {
int n = points.length;
// Lower bound is 0; an upper bound is:
// In the best case you might get about (1 + (m-1)/2) visits at a game,
// so the maximum score for any game is at most points[i]*(1+(m-1)/2).
// Hence the overall maximum possible minimum score is no more than
// min(points) * (1 + (m-1)/2).
long minPoint = Long.MAX_VALUE;
for (int p : points) {
if(p < minPoint) minPoint = p;
}
long hi = minPoint * (1 + (m - 1L) / 2);
long lo = 0, ans = 0;
while (lo <= hi) {
long mid = lo + (hi - lo) / 2;
if(feasible(mid, points, m)) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private boolean feasible(long X, int[] points, long m) {
int n = points.length;
if(X == 0) return true; // always feasible
long[] R = new long[n];
for (int i = 0; i < n; i++){
// Compute R[i] = ceil(X/points[i])
R[i] = (X + points[i] - 1) / points[i];
if(R[i] < 1) R[i] = 1;
}
int N = n - 1; // number of "edges" (k–variables)
// Pattern A:
long[] kA = new long[N];
if(N > 0) {
long A0 = R[0] - 1; // needed extra at game 0
kA[0] = A0;
for (int i = 1; i < N; i++) {
long req = R[i] - 1; // constraint for game i, 1<= i <= n-2
kA[i] = Math.max(req - kA[i - 1], 0);
}
// Finally, game n-1 must satisfy: 1 + kA[N-1] >= R[n-1]
long lastReq = R[n - 1] - 1;
if(kA[N - 1] < lastReq) {
kA[N - 1] = lastReq;
}
}
long S_A = 0;
for (int i = 0; i < N; i++) {
S_A += kA[i];
}
long costA = n + 2 * S_A;
// Pattern B:
long[] kB = new long[N];
if(N > 0) {
long A0 = R[0] - 1;
kB[0] = A0;
for (int i = 1; i < N; i++) {
long req = R[i] - 1;
kB[i] = Math.max(req - kB[i - 1], 0);
}
// For Pattern B, game n-1 must satisfy: v[n-1] = kB[N-1] >= R[n-1].
long lastReqB = R[n - 1];
if(kB[N - 1] < lastReqB) {
kB[N - 1] = lastReqB;
}
}
long S_B = 0;
for (int i = 0; i < N; i++) {
S_B += kB[i];
}
long costB = (n - 1) + 2 * S_B;
long minCost = Math.min(costA, costB);
return minCost <= m;
}
} | 0 | 0 | ['Binary Search', 'Dynamic Programming', 'Greedy', 'Java'] | 0 |
maximize-the-minimum-game-score | Simple binary search intuitive solution C++ | simple-binary-search-intuitive-solution-07lek | Code | VaidantJain | NORMAL | 2025-02-09T16:34:47.598751+00:00 | 2025-02-09T16:34:47.598751+00:00 | 44 | false |
# Code
```cpp []
class Solution {
public:
bool isValid(vector<int>&points, long long sol, long long m){
vector<long long> cnt;
for(int x : points) {
cnt.push_back((sol + x - 1) / x);
}
cnt.push_back(0);
long long move = 0;
for(int i = 0; i < points.size(); i++) {
if(i == points.size() - 1 && cnt[i] <= 0) break;
long long pm = max(0LL, cnt[i] - 1);
move += 1 + pm * 2;
if (i + 1 < cnt.size()) cnt[i+1] -= pm;
if(move > m) return false;
}
return move <= m;
}
long long maxScore(vector<int>& points, int m) {
int n=points.size();
if(m<n) return 0;
long long maxi = 0;
int ind=0, mini = INT_MAX;
for(int i=0;i<points.size();i++){
if(points[i]>maxi){
maxi = points[i];
ind = i;
}
mini= min(mini,points[i]);
}
long long start=mini, end = maxi*(m-ind+1)/2, ans=0;
while(start<=end){
long long mid = start + (end - start)/2;
vector<int>score(points.size());
if(isValid(points, mid,m)){
ans = max(ans,mid);
start = mid+1;
}
else{
end = mid-1;
}
}
return ans;
}
};
``` | 0 | 0 | ['Binary Search', 'C++'] | 0 |
maximize-the-minimum-game-score | ez c# | ez-c-by-ice__fizz-7uc8 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | ice__fizz | NORMAL | 2025-02-09T15:00:35.384841+00:00 | 2025-02-09T15:00:35.384841+00:00 | 11 | 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
```csharp []
public class Solution {
public long MaxScore(int[] points, int m) {
int n = points.Length;
if (m < n) return 0;
bool Can(long val) {
long total = 0, transfer = 0, skipAdd = 0;
for (int i = 0; i < n && total <= m; i++) {
int point = points[i];
long necessary = (val + point - 1) / point;
if (transfer >= necessary) {
transfer = 0;
skipAdd++;
} else {
long p = transfer * point;
long ops = ((val - p) + point - 1) / point;
total += 2 * ops - 1;
total += skipAdd;
transfer = Math.Max(ops - 1, 0);
skipAdd = 0;
}
}
return total <= m;
}
long left = 1, right = (long)1e18, ans = 0;
while (left <= right) {
long mid = left + (right - left) / 2;
if (Can(mid)) {
ans = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}
return ans;
}
}
``` | 0 | 0 | ['C#'] | 0 |
maximize-the-minimum-game-score | Python Hard | python-hard-by-lucasschnee-bv4i | null | lucasschnee | NORMAL | 2025-02-09T14:51:50.534965+00:00 | 2025-02-09T14:51:50.534965+00:00 | 15 | false | ```python3 []
class Solution:
def maxScore(self, points: List[int], m: int) -> int:
N = len(points)
mn = min(points)
mx = max(points)
def good(target):
carry = 0
moves = 0
i = 0
for x in points:
i += 1
cur = 0
cur += carry * x
if cur >= target and i == N:
break
cur += x
moves += 1
carry = 0
if cur >= target:
continue
diff = target - cur
amt = diff // x + int(diff % x > 0)
carry = amt
moves += amt * 2
# print(target, moves, m)
return moves <= m
l, r = 0, ((mx * m) // N) + mx * 2
best = 0
while l <= r:
mid = (l + r) // 2
if good(mid):
best = mid
l = mid + 1
else:
r = mid - 1
return best
``` | 0 | 0 | ['Python3'] | 0 |
maximize-the-minimum-game-score | Binary Search Simple Solution (Similar question and Striver Explanation link pasted) | binary-search-simple-solution-similar-qu-1n81 | IntuitionSimilar to this concepthttps://leetcode.com/problems/koko-eating-bananas/description/Striver Explanation on same approach--
I will highly recommend to | shivnath | NORMAL | 2025-02-09T14:20:53.519355+00:00 | 2025-02-09T14:20:53.519355+00:00 | 57 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Similar to this concept
https://leetcode.com/problems/koko-eating-bananas/description/
Striver Explanation on same approach--
I will highly recommend to watch this video before jumping to solve this question.
https://www.youtube.com/watch?v=R_Mfw4ew-Vo&t=2s
# Approach
<!-- Describe your approach to solving the problem. -->
Here we all allow to take atmost M moves and need to return maximum of minmum value after all moves.
now how to convert this problem in binary search - if are able to find the range of anser then we can apply binary serach on the answer space
let understand what we can be minimum and maximum possible value of our answer.
let suppose arr- [1,2,3] and m=2 and games[0,0,0]
so intially we are at index -1 after 1st operation our
operation =1, games[1,0,0]--- minimum1 =0
opretaion =2, games[1,2,0]--- minimum2 =0
now oprration over and we are having max(minimum1,minimum2)=0
so smallest possible answer is 0;
Observation if m<n then we can not traver complete array so answer will be 0.
let suppose arr [5,5,5] and m=6 and games[0,0,0]
op1 =1 , games[5,0,0]
op1 =2 , games[5,5,0]
op1 =3 , games[5,5,5]
op1 =4 , games[5,5,10]
op1 =5 , games[5,10,10]
op1 =6 , games[10,10,10]
so if arr size in n and maxval in arr=X then maximum possible answer will be X*(ceil(m/n)).
so now our left=0, right =maxValOfArray*(m/n);
and now our answer will be in range from left to right only. so we can apply binary search on this.
now slightly changing the problem.
we will create a function noOfOp() that will return no of opration required to make all vales of array altest mid.
where mid=(left+right)/2;
if noOfOperation > m : means to make all the vaule of array >=mid more operation are required so now this invalid so our range
do r-mid-1;
else
noOfOperation <= m : meanse this is one of possible ans , we can make all this element of array >=mid in less operation
so ans=mid, l=mid+1
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
Complexity of Function noOfOp O(N) where N is number of element in array .
Complexity of While loop used to generate possible answer is O(log(MaxPossibleValue) = 10^18)
so overall O(N*log(1e18))
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
We used one extra array games here on size N
so overall O(N).
**Note : If there is any mistake or Improvement please help .**
# Code
```cpp []
class Solution {
public:
double n=0;
long long noOfOp(vector<int>& points,long long m,vector<long long> & games)
{
long long noP=0;
long long noOfOperationR=0;
for(int i=0;i<n;i++)
{
if(i==n-1){
if(games[i]>=m)
return noP;
}
double valToBeAdded=m-games[i];
if(valToBeAdded<=points[i]){
games[i]+=points[i];
noP++;
continue;
}
long long noOfOperationRequired=ceil(valToBeAdded/points[i]);
if(noOfOperationRequired<=0)
noOfOperationRequired=1;
games[i]+=noOfOperationRequired*points[i];
if(i<n-1){
games[i+1]=(noOfOperationRequired-1)*points[i+1];
}
noP+=(noOfOperationRequired+noOfOperationRequired-1);
}
return noP;
}
long long maxScore(vector<int>& points, int m) {
n=points.size();
if(m<n) return 0;
long long maxVal=*max_element(points.begin(),points.end());
long long int times=double(ceil(double(m/n)));
long long r=0;
r =(maxVal*times);
long long l=0;
long long mid=0;
long long int ans=0;
while(l<=r){
mid=l+(r-l)/2;
vector<long long> games(n,0);
long long int op=noOfOp(points,mid,games);
if(op>m){
r=mid-1;
}else{
ans=mid;
l=mid+1;
}
}
return ans;
}
};
```
**Note : If there is any mistake or Improvement please help .** | 0 | 0 | ['Binary Search', 'C++'] | 0 |
maximize-the-minimum-game-score | [C++] Binary Search + Greedy | c-binary-search-greedy-by-projectcoder-e5yq | Code | projectcoder | NORMAL | 2025-02-09T10:52:10.753435+00:00 | 2025-02-09T10:52:10.753435+00:00 | 43 | false |
# Code
```cpp []
typedef long long ll;
class Solution {
public:
long long maxScore(vector<int>& a, int T) { int n = a.size();
auto check = [&](ll limit) -> bool {
ll s = 0, e = 0, k = 0;
for (int i = 1; i <= n; i++) {
k = (limit-1)/a[i-1] + 1;
if (i == n && k <= e) break;
e++;
s += max(k, e);
e = max(k-e, 0ll);
}
return s+e <= T;
};
ll l = 1, r = 1e15;
while (l <= r) {
ll mid = (l+r)>>1;
if (check(mid)) l = mid+1;
else r = mid-1;
}
return r;
}
};
``` | 0 | 0 | ['C++'] | 0 |
maximize-the-minimum-game-score | Binary Search | binary-search-by-maxorgus-b42s | Binary search, below is the explanation for the 'possible' function. Reat are trivial BS roadmaps.Fix the minimum value x we want to getGo over the pointsWhen v | MaxOrgus | NORMAL | 2025-02-09T09:56:24.847037+00:00 | 2025-02-09T09:56:24.847037+00:00 | 19 | false | Binary search, below is the explanation for the 'possible' function. Reat are trivial BS roadmaps.
Fix the minimum value x we want to get
Go over the points
When visiting index i, it costs on jump. Suppose we have visited t times the index i where the point is p, subtract i*(p+1) from x (+1 comes from the operation when jumping here), if x <=i*(p+1), it means we don't have to hop back and forth at this position when should go to the next index, if not,
calculate x - i*(p+1) which is the remaining amount to be added, and it's easy to know how many times we have to visit this index again, suppose it is t. The quickliest way to visit a certain index again would be to jump to the next and come back, so we make additional 2*t jumps to achieve this, and t should be recorded to the next index where t*points[i+1] would be forehandedly removed.
When the number of jumps runs out of the resevoir of m times, return False for this attempt of x,
A subtle corner case happens at the last index, if when visiting index N-2 when jumped to N-1 t times and t*points[-1] >= x already, we don't have to go to the last index again, in which case even if the remaining hops is less than 0 x also stands.
# Code
```python3 []
class Solution:
def maxScore(self, points: List[int], m: int) -> int:
N = len(points)
if m < N:return 0
elif m == N: return min(points) // corner cases where we have less than N or equal to N jumps in which case the results are trivial
def possible(x):
hops = m
prevt = 0
for i,a in enumerate(points):
A = a*(prevt+1)
hops -= 1
if A < x:
t = (x - A)// a + int((x - A)% a != 0)
else:
t = 0
if i == N-1:
if A-a<x and hops == -1:return False
return True
prevt = t
hops -= t*2
if hops < 0: return False
return True
mm,MM = min(points),max(points)
l,r = 0,MM*m
while l < r:
mid = (l+r) // 2
t = possible(mid)
if t:
l = mid + 1
else:
r = mid
return max(0,l-1)
``` | 0 | 0 | ['Binary Search', 'Python3'] | 0 |
maximize-the-minimum-game-score | Rust Solution | rust-solution-by-abhineetraj1-079e | IntuitionThe problem involves determining the maximum score that can be achieved under the constraint of performing no more than m operations on a given set of | abhineetraj1 | NORMAL | 2025-02-09T08:31:41.288894+00:00 | 2025-02-09T08:31:41.288894+00:00 | 16 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem involves determining the maximum score that can be achieved under the constraint of performing no more than m operations on a given set of points. A brute force approach would not be efficient, especially if the values of n and m are large. Hence, a more efficient solution is required, and this can be achieved using binary search and greedy strategies. The intuition is that if we can achieve a certain score using m or fewer operations, we can attempt a higher score and check if it remains feasible. This makes binary search a perfect fit for optimizing the score.
# Approach
<!-- Describe your approach to solving the problem. -->
The problem is solved using binary search to determine the maximum achievable score within m operations. We start by defining a range for the score, from 1 to a large upper bound (1e18). For each midpoint score, we check if it's possible to achieve it with no more than m operations using a greedy approach. In the greedy approach, we try to minimize the number of operations by utilizing previously accumulated "transfer" values from earlier points. If the score can be achieved within m operations, we move to higher scores by adjusting the binary search bounds, otherwise, we search for lower scores. This process continues until the maximum possible score is found. The binary search helps efficiently narrow down the optimal score, and the feasibility check ensures that we don't exceed the operation limit.
# Complexity
- Time complexity: O(n⋅log(max_score))
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```rust []
impl Solution {
pub fn max_score(points: Vec<i32>, m: i32) -> i64 {
let n = points.len();
if m < n as i32 {
return 0;
}
let mut left = 1;
let mut right = 1e18 as i64;
let mut ans = 0;
while left <= right {
let mid = left + (right - left) / 2;
if Self::can_achieve(&points, n, m, mid) {
ans = mid;
left = mid + 1;
} else {
right = mid - 1;
}
}
ans
}
fn can_achieve(points: &Vec<i32>, n: usize, m: i32, val: i64) -> bool {
let mut total = 0;
let mut transfer = 0;
let mut skip_add = 0;
for i in 0..n {
if total > m as i64 {
break;
}
let point = points[i] as i64;
let necessary = (val + point - 1) / point;
if transfer >= necessary {
transfer = 0;
skip_add += 1;
} else {
let p = transfer * point;
let ops = ((val - p) + point - 1) / point;
total += 2 * ops - 1;
total += skip_add;
transfer = std::cmp::max(ops - 1, 0);
skip_add = 0;
}
}
total <= m as i64
}
}
``` | 0 | 0 | ['Binary Search', 'Dynamic Programming', 'Rust'] | 0 |
maximize-the-minimum-game-score | Binary search [Python3] | binary-search-python3-by-kevin_pan-pghi | Binary search for the maximum minimum value. For a value x, try to make every element in the array at least x.
We need to visit each index at least once if x is | kevin_pan | NORMAL | 2025-02-09T04:59:37.311415+00:00 | 2025-02-09T05:01:00.428662+00:00 | 28 | false | Binary search for the maximum minimum value. For a value $$x$$, try to make every element in the array at least $$x$$.
We need to visit each index at least once if $$x$$ is non-zero. It is optimal to traverse left to right and alternate between adjacent indices to satisfy the minimum value.
# Complexity
Let M be the maximum possible value of the an element in `gameScore`
- Time complexity: $$\mathcal{O}(M\log{N})$$
- Space complexity: $$\mathcal{O}(1)$$
# Code
```python3 []
class Solution:
def maxScore(self, points: List[int], m: int) -> int:
n = len(points)
def valid(x):
last = 0
moves = 0
for i in range(n):
div = (x + points[i] - 1) // points[i]
curr = (div * 2) - 1
if last > 1:
curr = max(0 if i == n - 1 else 1, curr - last + 1)
moves += curr
if moves > m:
return False
last = curr
return True
lo, hi = 0, 10 ** 15
while lo < hi:
mid = (lo + hi) // 2 + 1
if valid(mid):
lo = mid
else:
hi = mid - 1
return lo
``` | 0 | 0 | ['Python3'] | 0 |
maximize-the-minimum-game-score | Not very hard, but prone to bugs | not-very-hard-but-prone-to-bugs-by-metap-q7s6 | IntuitionThe framework is simple: binary search for finding the answer.ApproachTo check if an answer t is valid, we simulate the process from i = -1 to n-1.
For | metaphysicalist | NORMAL | 2025-02-09T04:38:27.354530+00:00 | 2025-02-09T05:02:31.738831+00:00 | 58 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The framework is simple: binary search for finding the answer.
# Approach
<!-- Describe your approach to solving the problem. -->
To check if an answer `t` is valid, we simulate the process from `i = -1` to `n-1`.
For making `scores[i] >= t`, we require `2 * ceil(t/points[i])` steps for moving between `i` and `i+1`, and `scores[i+1]` will also receive the `ceil(t/points[i]) * points[i+1]` points.
Take care the edge cases.
# Complexity
- Time complexity: $O(N \log M)$, where $M$ is $10^6 \times 10^9=10^{15}$
- Space complexity: $O(1)$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
# Code
```python3
class Solution:
def maxScore(self, points: List[int], m: int) -> int:
n = len(points)
def check(t):
score = 0
step = 0
j = -1
for i in range(n):
if score >= t:
score = 0
continue
step += (i - j)
score += points[i]
j = i
r = (t - score + points[i] - 1) // points[i]
step += r * 2
if step > m:
return False
if i + 1 < n:
score = points[i+1] * r
return True
l, r = 0, min(points) * m + 1
while l < r:
mid = (l + r) // 2
if check(mid):
l = mid + 1
else:
r = mid
return l - 1
``` | 0 | 0 | ['Binary Search', 'Simulation', 'Python3'] | 0 |
maximize-the-minimum-game-score | C++ | c-by-user5976fh-tcmx | null | user5976fh | NORMAL | 2025-02-09T04:25:45.010840+00:00 | 2025-02-09T04:54:12.560642+00:00 | 36 | false | ```cpp []
class Solution {
public:
long long maxScore(vector<int>& points, int m) {
long long ans = 0, l = 0, r = 1e16;
vector<long long> p(points.begin(), points.end());
while (l <= r){
long long mid = (l + r) / 2;
if (valid(mid, p, m)) ans = mid, l = mid + 1;
else r = mid - 1;
}
return ans;
}
bool valid(long long mid, vector<long long>& p, int m){
long long totalMoves = 1, prevGain = 1;
for (int i = 0; i < p.size(); ++i){
double cur = prevGain;
cur *= p[i];
if (cur < mid){
long long dif = mid - cur;
prevGain = (dif / p[i] + (dif % p[i] > 0));
totalMoves += 2 * prevGain;
if (i + 1 == p.size() || (i + 2 == p.size() && prevGain * p[i + 1] >= mid))
break;
else ++prevGain, ++totalMoves;
}
else{
prevGain = 1, totalMoves += i + 1 != p.size();
}
}
return totalMoves <= m;
}
};
``` | 0 | 0 | ['C++'] | 0 |
maximize-the-minimum-game-score | [C++] Greedy + Binary Search Explained | c-greedy-binary-search-by-yvi55kfihx-kwhd | IntuitionGiven a specific maximum possible minimum value (MPM), you can check whether it can be fulfiled within m moves in O(N) time.
Use binary search to narr | YVI55KFiHX | NORMAL | 2025-02-09T04:16:07.078086+00:00 | 2025-02-09T04:24:21.204447+00:00 | 111 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Given a specific **maximum possible minimum** value (MPM), you can check whether it can be fulfiled within m moves in O(N) time.
1. Use binary search to narrow down the search space of possible **maximum possible minimum** values. `O(log N)`
2. Within each check, at every `point[i]`, the best way to fulfil the **MPM** at `point[i]` is to pivot back and forth between i and i + 1.
(Idk how to prove this, but it seemed better than the alternate traversal choices)

Therefore, you need to track 3 things at each `i`:
1) Cost of travelling from previous index to `i`.
2) Cost of fulfilling **MPM** at i, which is `MPM / points[i]` + `1 if not divisible`.
3) Since you pivot using `i+1`, you can subtract some usage from `i+1`.
# Code
```cpp []
class Solution {
public:
using ll = long long;
bool fulfilConditions(vector<long long>& points, long long m, long long mid) {
int lastIndex = -1;
int n = points.size();
vector<ll> decrement(n);
for (int i = 0; i < n; ++i) {
if (m < 0) return false;
ll toAdd = 0;
if ((mid % points[i]) == 0) {
//cout << "divisible" << endl;
toAdd += (mid / points[i]);
} else {
//cout << "not divisible" << endl;
toAdd += (mid/points[i]) + 1;
}
toAdd += decrement[i];
//printf("At index %d: toAdd %lld mid %lld points[i] %lld decrement[i] %lld\n", i, toAdd, mid, points[i], decrement[i]);
if (toAdd > 0) {
ll dist = i - lastIndex;
ll currUsage = toAdd - 1; // minus 1 because cost already counted in the distance to reach i
ll nextUsage = toAdd - 1;
//printf("At index %d: dist %lld currUsage %lld nextUsage %lld\n", i, dist, currUsage, nextUsage);
m -= dist;
m -= currUsage;
m -= nextUsage;
if (i+1 < n) decrement[i+1] -= nextUsage;
lastIndex = i;
}
}
return m >= 0;
}
long long maxScore(vector<int>& points, int m) {
long long left = 0, right = LLONG_MAX;
vector<ll> newpoints;
for (auto p : points) newpoints.push_back(p);
while (left < right) {
ll mid = right - ((right - left) / 2);
//printf("[%d %d %d]\n", left, mid, right);
if (fulfilConditions(newpoints, m, mid)) {
left = mid;
} else {
right = mid - 1;
}
}
return left;
}
};
``` | 0 | 0 | ['C++'] | 0 |
surface-area-of-3d-shapes | [C++/Java/1-line Python] Minus Hidden Area | cjava1-line-python-minus-hidden-area-by-5ms83 | Intuition:\nFor each tower, its surface area is 4 * v + 2\nHowever, 2 adjacent tower will hide the area of connected part.\nThe hidden part is min(v1, v2) and w | lee215 | NORMAL | 2018-08-26T03:01:27.146921+00:00 | 2018-10-24T22:24:45.757523+00:00 | 12,098 | false | **Intuition**:\nFor each tower, its surface area is `4 * v + 2`\nHowever, 2 adjacent tower will hide the area of connected part.\nThe hidden part is `min(v1, v2)` and we need just minus this area * 2\n\n**Time Complexity**:\nO(N^2)\n\n**C++:**\n```\n int surfaceArea(vector<vector<int>> grid) {\n int res = 0, n = grid.size();\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < n; ++j) {\n if (grid[i][j]) res += grid[i][j] * 4 + 2;\n if (i) res -= min(grid[i][j], grid[i - 1][j]) * 2;\n if (j) res -= min(grid[i][j], grid[i][j - 1]) * 2;\n }\n }\n return res;\n }\n```\n\n**Java:**\n```\n public int surfaceArea(int[][] grid) {\n int res = 0, n = grid.length;\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < n; ++j) {\n if (grid[i][j] > 0) res += grid[i][j] * 4 + 2;\n if (i > 0) res -= Math.min(grid[i][j], grid[i - 1][j]) * 2;\n if (j > 0) res -= Math.min(grid[i][j], grid[i][j - 1]) * 2;\n }\n }\n return res;\n }\n```\n**Python:**\n```\n def surfaceArea(self, grid):\n n, res = len(grid), 0\n for i in range(n):\n for j in range(n):\n if grid[i][j]: res += 2 + grid[i][j] * 4\n if i: res -= min(grid[i][j], grid[i - 1][j]) * 2\n if j: res -= min(grid[i][j], grid[i][j - 1]) * 2\n return res\n```\n\n**1-line Python:**\n```\n def surfaceArea(self, grid):\n return sum(v * 4 + 2 for row in grid for v in row if v) - sum(min(a, b) * 2 for row in grid + zip(*grid) for a, b in zip(row, row[1:]))\n``` | 289 | 3 | [] | 34 |
surface-area-of-3d-shapes | 892. Surface Area of 3D Shapes. C++ solution with visual presentation | 892-surface-area-of-3d-shapes-c-solution-rl6s | Surface area of 1 cube is equal to 6 according to description (1 * 1 * 1) * 6, cube have 6 sides.\ngrid[i][j] is a count of cubes placed on top of grid cell. Fo | langrenn | NORMAL | 2020-01-07T09:55:30.534076+00:00 | 2020-03-21T16:37:23.287519+00:00 | 3,266 | false | Surface area of 1 cube is equal to 6 according to description (1 * 1 * 1) * 6, cube have 6 sides.\ngrid[i][j] is a count of cubes placed on top of grid cell. For instance, if we have a grid[i][j] = 2, it means we placed two cubes one on other and they have a common area is equal to 2, because we have two connected sides. If the grid[i][j] = 3, then common area is equal to 4. \nIt turns out when grid[i][j] is equal to:\n2 cubes - 2\n3 cubes - 4\n4 cubes - 6\n5 cubes - 8 => **2 * (grid[i][j] - 1)**\nWe also have to substract common area on **y** and **x** axis. We only compute up to **n - 1** for both axis by calculating minimum of two connected **V**s and multiply by 2.\nRed squares is a common areas which we have to subtract from resulting total surface area.\nThe following depicted picture shows example: [[2, 3, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]. The answer is: 5 * 6 - 2 - 4 = 20.\n\n\n\n```\nint surfaceArea(vector<vector<int>>& grid) {\n\tint n = grid.size();\n\tint res = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tif (grid[i][j] == 0) continue;\n\t\t\tres += grid[i][j] * 6 - 2 * (grid[i][j] - 1); \n\t\t\tif (i < n - 1) res -= 2 * min(grid[i][j], grid[i+1][j]);\n\t\t\tif (j < n - 1) res -= 2 * min(grid[i][j], grid[i][j+1]); \n\t\t}\n\t}\n\treturn res;\n}\n```\n**Complexity Analysis**:\n\nTime Complexity: **O(n\xB2)**, where N is the number of rows (and columns) in the grid.\n\nSpace Complexity: **O(1)**. | 40 | 0 | ['Geometry', 'C'] | 6 |
surface-area-of-3d-shapes | Simple Python explained | simple-python-explained-by-sunakshi132-ruhr | \nclass Solution:\n def surfaceArea(self, grid: List[List[int]]) -> int:\n \n l = len(grid)\n area=0\n for row in range(l):\n | sunakshi132 | NORMAL | 2022-07-25T00:52:52.416545+00:00 | 2022-07-25T00:52:52.416588+00:00 | 1,973 | false | ```\nclass Solution:\n def surfaceArea(self, grid: List[List[int]]) -> int:\n \n l = len(grid)\n area=0\n for row in range(l):\n for col in range(l):\n if grid[row][col]:\n area += (grid[row][col]*4) +2 #surface area of each block if blocks werent connected\n if row: #row>0\n area -= min(grid[row][col],grid[row-1][col])*2 #subtracting as area is common among two blocks\n if col: #col>0\n area -= min(grid[row][col],grid[row][col-1])*2 #subtracting as area is common among two blocks\n return area\n``` | 11 | 0 | ['Python', 'Python3'] | 0 |
surface-area-of-3d-shapes | [Java] 1 pass 9 line concise code, find contact surface area difference . | java-1-pass-9-line-concise-code-find-con-86hb | Compute the cubes\' contact surface area difference in x and y directions, recpectively; as for the area seen along z-axis, count the number of non-zero values | rock | NORMAL | 2018-08-26T03:04:42.969754+00:00 | 2018-08-26T05:51:05.149319+00:00 | 848 | false | Compute the cubes\' **contact surface area difference** in x and y directions, recpectively; as for the area seen along z-axis, count the number of non-zero values and times 2.\n\n```\n public int surfaceArea(int[][] grid) {\n int x = 0, y = 0, z = 0, n = grid.length;\n for (int i = 0; i < n; x += grid[n - 1][i], y += grid[i][n - 1], ++i) { // do NOT forget the surface at (n - 1, i) and (i, n - 1).\n for (int j = 0; j < n; ++j) {\n x += Math.abs(grid[j][i] - (j > 0 ? grid[j - 1][i] : 0)); // dummy value for grid[-1][i] is 0.\n y += Math.abs(grid[i][j] - (j > 0 ? grid[i][j - 1] : 0)); // dummy value for grid[i][-1] is 0.\n z += grid[i][j] > 0 ? 2 : 0;\n }\n }\n return x + y + z; \n }\n``` | 8 | 0 | [] | 1 |
surface-area-of-3d-shapes | Python | Easy | Matrix | Surface Area of 3D Shapes | python-easy-matrix-surface-area-of-3d-sh-nnh3 | \nsee the Successfully Accepted Submission\nPython\nclass Solution(object):\n def surfaceArea(self, grid):\n n = len(grid)\n res = 0\n\n | Khosiyat | NORMAL | 2023-10-07T15:06:01.566216+00:00 | 2023-10-07T15:06:01.566236+00:00 | 305 | false | \n[see the Successfully Accepted Submission](https://leetcode.com/submissions/detail/1066993426/)\n```Python\nclass Solution(object):\n def surfaceArea(self, grid):\n n = len(grid)\n res = 0\n\n for i in range(n):\n for j in range(n):\n if grid[i][j] == 0:\n continue\n res += grid[i][j] * 6 - 2 * (grid[i][j] - 1)\n\n if i < n - 1:\n res -= 2 * min(grid[i][j], grid[i + 1][j])\n\n if j < n - 1:\n res -= 2 * min(grid[i][j], grid[i][j + 1])\n\n return res\n```\n\n**Intuituin**\n \nGet the size of the grid (assuming it\'s a square grid)\n```\n n = len(grid)\n```\n Initialize the result variable to accumulate the surface area\n```\n res = 0 \n```\n\nSkip cells with zero height (they don\'t contribute to the surface area)\n```\n for i in range(n):\n for j in range(n):\n if grid[i][j] == 0:\n continue \n```\n\nCalculate the surface area contributed by a single cube (6 times its height)\n```\n cube_area = grid[i][j] * 6\n```\n\nSubtract the surface area of hidden sides (2 times the number of adjacent cubes minus one)\n```\n hidden_sides = (grid[i][j] - 1) * 2\n```\n \nAdd the net surface area contributed by the current cube to the result\n```\n res += cube_area - hidden_sides\n```\n \nCheck for adjacent cubes in the down direction (i+1) and right direction (j+1)\n\n- Subtract the common area between adjacent cubes\n```\n if i < n - 1:\n res -= 2 * min(grid[i][j], grid[i + 1][j]) \n```\n\n- Subtract the common area between adjacent cubes\n```\n if j < n - 1:\n res -= 2 * min(grid[i][j], grid[i][j + 1]) \n```\n Return the total surface area\n ```\n return res\n```\n\n\n\n\n | 6 | 0 | ['Matrix', 'Python'] | 0 |
surface-area-of-3d-shapes | JavaScript solution | javascript-solution-by-shengdade-dfpl | javascript\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar surfaceArea = function(grid) {\n const height = grid.length;\n const width = grid[ | shengdade | NORMAL | 2020-02-17T21:48:43.118765+00:00 | 2020-02-17T21:48:43.118816+00:00 | 433 | false | ```javascript\n/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar surfaceArea = function(grid) {\n const height = grid.length;\n const width = grid[0].length;\n let sum = 0;\n for (let i = 0; i < height; i++) {\n for (let j = 0; j < width; j++) {\n if (grid[i][j] > 0) sum += grid[i][j] * 4 + 2;\n if (i > 0) sum -= 2 * Math.min(grid[i - 1][j], grid[i][j]);\n if (j > 0) sum -= 2 * Math.min(grid[i][j - 1], grid[i][j]);\n }\n }\n return sum;\n};\n```\n\n* 90/90 cases passed (52 ms)\n* Your runtime beats 100 % of javascript submissions\n* Your memory usage beats 100 % of javascript submissions (34.7 MB) | 6 | 0 | ['JavaScript'] | 1 |
surface-area-of-3d-shapes | Python easy-to-understand solution (52ms) | python-easy-to-understand-solution-52ms-xi05o | \nclass Solution:\n def surfaceArea(self, grid):\n """\n :type grid: List[List[int]]\n :rtype: int\n """\n n = len(grid)\n | kyungminlee | NORMAL | 2018-12-13T00:28:10.819028+00:00 | 2018-12-13T00:28:10.819074+00:00 | 1,065 | false | ```\nclass Solution:\n def surfaceArea(self, grid):\n """\n :type grid: List[List[int]]\n :rtype: int\n """\n n = len(grid)\n m = len(grid[0])\n \n\t\t# surfaces perpendicular to x-axis\n area_x = 0\n for i in range(n):\n prev_height = 0 \n for j in range(m):\n area_x += abs(grid[i][j] - prev_height)\n prev_height = grid[i][j]\n area_x += prev_height\n\n\t\t# surfaces perpendicular to y-axis\n area_y = 0\n for j in range(m):\n prev_height = 0 \n for i in range(n):\n area_y += abs(grid[i][j] - prev_height)\n prev_height = grid[i][j]\n area_y += prev_height\n \n\t\t# surfaces perpendicular to z-axis (top and bottom)\n area_z = 0\n for i in range(n):\n for j in range(m):\n if grid[i][j] != 0:\n area_z += 2\n \n return area_x + area_y + area_z\n``` | 6 | 0 | [] | 2 |
surface-area-of-3d-shapes | Java simple solution | java-simple-solution-by-geeksnap-35ed | Surface area of a cube = 6*(side)^2 (In this problem side = 1)\n2. If the value in grid[i][j] > 1 i.e. top/bottom will overlap; subtract 2\n3. check for previou | geeksnap | NORMAL | 2018-08-26T03:56:50.569173+00:00 | 2018-10-18T02:46:24.879077+00:00 | 1,571 | false | 1. Surface area of a cube = 6*(side)^2 (In this problem side = 1)\n2. If the value in grid[i][j] > 1 i.e. top/bottom will overlap; subtract 2\n3. check for previous row and previous column for any overlapping too\n\n```\nclass Solution {\n public int surfaceArea(int[][] grid) {\n int res = 0;\n \n if(grid == null || grid.length == 0 || grid[0].length==0) {\n return res;\n }\n \n for(int i=0;i<grid.length;i++) {\n for(int j=0;j<grid[i].length;j++) {\n res+=grid[i][j]*6;\n \n if(grid[i][j] > 1) {\n res-=(grid[i][j]-1)*2;\n }\n \n if(i>=0 && i-1>=0) {\n res-=Math.min(grid[i][j], grid[i-1][j])*2;\n }\n \n if(j>=0 && j-1>=0) {\n res-=Math.min(grid[i][j], grid[i][j-1])*2;\n }\n }\n }\n \n return res;\n }\n}\n``` | 6 | 0 | [] | 1 |
surface-area-of-3d-shapes | Simple java code 1 ms beats 100 % | simple-java-code-1-ms-beats-100-by-arobh-clmt | \n# Complexity\n\n\n# Code\n\nclass Solution {\n public int surfaceArea(int[][] grid) {\n int result = 0;\n for (int i = 0; i < grid.length; i+ | Arobh | NORMAL | 2024-05-10T15:05:49.555965+00:00 | 2024-05-10T15:05:49.556002+00:00 | 451 | false | \n# Complexity\n\n\n# Code\n```\nclass Solution {\n public int surfaceArea(int[][] grid) {\n int result = 0;\n for (int i = 0; i < grid.length; i++) for (int j = 0; j < grid[0].length; j++) result += getArea(grid, i, j);\n return result;\n }\n private int getArea(int[][] grid, int i, int j) {\n int towerHeight = grid[i][j];\n if (towerHeight == 0) return 0;\n int area = 2 + (towerHeight * 4);\n if (i > 0) area -= Math.min(towerHeight, grid[i - 1][j]);\n if (i < grid.length - 1) area -= Math.min(towerHeight, grid[i + 1][j]);\n if (j > 0) area -= Math.min(towerHeight, grid[i][j - 1]);\n if (j < grid[0].length - 1) area -= Math.min(towerHeight, grid[i][j + 1]);\n return area;\n }\n}\n``` | 5 | 0 | ['Array', 'Math', 'Geometry', 'Matrix', 'Java'] | 0 |
surface-area-of-3d-shapes | C++ | Very Easy Code with Explanation | c-very-easy-code-with-explanation-by-ank-9p1u | Please Upvote :)\n\n\nclass Solution {\npublic:\n int surfaceArea(vector<vector<int>>& grid) {\n int res=0;\n for(int i=0;i<grid.size();i++)\n | ankit4601 | NORMAL | 2022-07-24T09:08:30.840709+00:00 | 2022-07-24T09:08:30.840738+00:00 | 1,009 | false | Please Upvote :)\n\n```\nclass Solution {\npublic:\n int surfaceArea(vector<vector<int>>& grid) {\n int res=0;\n for(int i=0;i<grid.size();i++)\n {\n for(int j=0;j<grid[0].size();j++)\n {\n if(grid[i][j])\n {\n res+=2; // 1 for up, 1 for down\n res+=fun(grid,i-1,j,grid[i][j]);// left\n res+=fun(grid,i,j-1,grid[i][j]);// front\n res+=fun(grid,i+1,j,grid[i][j]);// right\n res+=fun(grid,i,j+1,grid[i][j]);// back\n }\n }\n }\n return res;\n }\n int fun(vector<vector<int>>& grid,int i,int j,int val)\n {\n if(i<0 || j<0 || i>=grid.size() || j>=grid[0].size())\n return val;// if no adjacent cube then total area is contributed\n \n if(grid[i][j]<val) // if neighbour cube is there then the diff is contributed\n return val-grid[i][j];\n \n return 0; // if the current is smaller than its neighbour, no contribution\n }\n};\n``` | 5 | 0 | ['C', 'C++'] | 0 |
surface-area-of-3d-shapes | Python solution | python-solution-by-faceplant-rhc5 | \tresult = 0\n\tfor i in range(len(grid)):\n\t\tfor j in range(len(grid)):\n\t\t\tif grid[i][j] > 0:\n\t\t\t\tresult += grid[i][j] * 4 + 2\n\t\t\t\tif i + 1 < l | FACEPLANT | NORMAL | 2021-01-17T15:50:01.694127+00:00 | 2021-01-17T15:50:01.694175+00:00 | 509 | false | \tresult = 0\n\tfor i in range(len(grid)):\n\t\tfor j in range(len(grid)):\n\t\t\tif grid[i][j] > 0:\n\t\t\t\tresult += grid[i][j] * 4 + 2\n\t\t\t\tif i + 1 < len(grid):\n\t\t\t\t\tresult -= min(grid[i][j], grid[i + 1][j]) * 2\n\t\t\t\tif j + 1 < len(grid):\n\t\t\t\t\tresult -= min(grid[i][j], grid[i][j + 1]) * 2\n\treturn result | 5 | 0 | [] | 1 |
surface-area-of-3d-shapes | [Python] faster than 99%, compute only three faces then get the answer | python-faster-than-99-compute-only-three-3cmq | python\nclass Solution:\n def surfaceArea(self, grid):\n top = 0\n for row in grid:\n for num in row:\n if num > 0:\n | kuanc | NORMAL | 2019-08-29T15:38:28.092768+00:00 | 2019-08-29T15:38:28.092805+00:00 | 579 | false | ```python\nclass Solution:\n def surfaceArea(self, grid):\n top = 0\n for row in grid:\n for num in row:\n if num > 0:\n top += 1\n\n left = 0\n for row in grid:\n std = 0\n for num in row:\n if num - std > 0:\n left += num - std\n std = num\n\n front = 0\n for i in range(len(grid[0])):\n std = 0\n for row in grid:\n if row[i] - std > 0:\n front += row[i] - std\n std = row[i]\n\n return 2 * (top + left + front)\n``` | 5 | 0 | ['Python'] | 2 |
surface-area-of-3d-shapes | Python - simple explanation | python-simple-explanation-by-aac123-gkhv | The surface area of a rectangular prism of height h sitting on a 1x1 square = 2 + 4 * h.\n\nThe overlap (double counting) of surface area between a prism and a | aac123 | NORMAL | 2020-09-05T02:13:29.403670+00:00 | 2020-09-05T02:22:34.148223+00:00 | 304 | false | The surface area of a rectangular prism of height h sitting on a 1x1 square = 2 + 4 * h.\n\nThe overlap (double counting) of surface area between a prism and a neighboring prism is 2 * min(h(curr), h(nei)). This is because each of the two prisms is double counting the face that touches, e.g. the face that represents the minimum of the two heights.\n\nWe only want to look at neighbors that are behind the current prism in either direction (e.g. left or above) to subtract the double counted faces. Alteratively, you could also subtract neighbors ahead of the current prism (right or below) and change the if statement logic to i < len(grid) - 1, j < len(grid[0]) - 1.\n\n```\nclass Solution:\n def surfaceArea(self, grid: List[List[int]]) -> int:\n sa = 0\n \n for i in range(len(grid)):\n for j in range(len(grid[0])):\n curr = grid[i][j]\n if curr:\n sa += 2 + 4 * curr\n if i > 0:\n sa -= 2 * min(grid[i-1][j], curr)\n if j > 0:\n sa -= 2 * min(grid[i][j-1], curr)\n \n return sa\n```\n\n\n | 4 | 0 | [] | 0 |
surface-area-of-3d-shapes | C++ || 99.97% faster || Easy to understand | c-9997-faster-easy-to-understand-by-anon-aabz | \nclass Solution {\npublic:\n int surfaceArea(vector<vector<int>>& grid) {\n int result = 0;\n for(int i=0;i<grid.size();i++){\n for | anonymous_kumar | NORMAL | 2020-06-29T07:08:36.419741+00:00 | 2020-06-29T07:09:53.277594+00:00 | 487 | false | ```\nclass Solution {\npublic:\n int surfaceArea(vector<vector<int>>& grid) {\n int result = 0;\n for(int i=0;i<grid.size();i++){\n for(int j=0;j<grid[0].size();j++){\n int val = grid[i][j];\n if(val >= 2){\n result += 10 + 4 * (val - 2);\n }else{\n result += 6 * val;\n }\n \n if(i-1 >= 0 && grid[i-1][j] > 0){\n result -= 2*min(val,grid[i-1][j]);\n }\n if(j-1 >= 0 && grid[i][j-1] > 0){\n result -= 2*min(val,grid[i][j-1]);\n }\n }\n }\n return result;\n }\n};\n```\n*Please comment, if you have any query!!!*\n**Please upvote, if you like the solution.** | 4 | 1 | ['C', 'C++'] | 0 |
surface-area-of-3d-shapes | Javascript easy solution! | javascript-easy-solution-by-bundit-8y4c | We first add the whole surface area of the tower. Then we subtract the overlapping \'walls.\' \nDo this for every tower.\n\nvar surfaceArea = function(grid) {\n | bundit | NORMAL | 2018-12-12T04:55:25.611115+00:00 | 2018-12-12T04:55:25.611183+00:00 | 257 | false | We first add the whole surface area of the tower. Then we subtract the overlapping \'walls.\' \nDo this for every tower.\n```\nvar surfaceArea = function(grid) {\n let area = 0;\n \n for (let i in grid) {\n for (let j in grid) {\n\t\t\n if (grid[i][j]) { \n area += (grid[i][j] * 4) + 2;\n if (i > 0) area -= 2 * Math.min(grid[i][j], grid[i-1][j]);\n if (j > 0) area -= 2 * Math.min(grid[i][j], grid[i][j-1]);\n }\n }\n }\n \n return area;\n};\n``` | 4 | 0 | [] | 0 |
surface-area-of-3d-shapes | Python iterative solution | python-iterative-solution-by-cenkay-fxmw | Surface area of each cell is 4 * lateral area + upper and lower face unit areas.\n* For each cell, neighbour cells blocks some area, which is the minimum of 2 c | cenkay | NORMAL | 2018-08-26T07:09:30.206336+00:00 | 2018-10-24T22:23:05.527760+00:00 | 306 | false | * Surface area of each cell is 4 * lateral area + upper and lower face unit areas.\n* For each cell, neighbour cells blocks some area, which is the minimum of 2 cells taken into account.\n```\nclass Solution:\n def surfaceArea(self, grid):\n n, sm = len(grid), 0\n for i in range(n):\n for j in range(n):\n if grid[i][j]:\n sm += grid[i][j] * 4 + 2\n sm -= i and min(grid[i - 1][j], grid[i][j])\n sm -= j and min(grid[i][j - 1], grid[i][j])\n sm -= i < n - 1 and min(grid[i + 1][j], grid[i][j])\n sm -= j < n - 1 and min(grid[i][j + 1], grid[i][j])\n return sm\n``` | 4 | 0 | [] | 0 |
surface-area-of-3d-shapes | Java Understandable Solution | java-understandable-solution-by-tbekpro-bcli | Code\n\nclass Solution {\n public int surfaceArea(int[][] grid) {\n int sum = 0;\n for (int i = 0; i < grid.length; i++) {\n for (in | tbekpro | NORMAL | 2022-12-13T05:51:43.504048+00:00 | 2022-12-13T05:51:43.504074+00:00 | 1,364 | false | # Code\n```\nclass Solution {\n public int surfaceArea(int[][] grid) {\n int sum = 0;\n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid[0].length; j++) {\n int h = grid[i][j];\n int fullS = h > 0 ? h * 4 + 2 : 0;\n //check adjacent and substract touching surface\n //check left\n if (cellExists(i, j - 1, grid)) {\n if (h <= grid[i][j - 1]) {\n fullS -= h;\n } else {\n fullS -= grid[i][j - 1];\n }\n }\n //check up\n if (cellExists(i - 1, j, grid)) {\n if (h <= grid[i - 1][j]) {\n fullS -= h;\n } else {\n fullS -= grid[i - 1][j];\n }\n }\n //check right\n if (cellExists(i, j + 1, grid)) {\n if (h <= grid[i][j + 1]) {\n fullS -= h;\n } else {\n fullS -= grid[i][j + 1];\n }\n }\n //check down\n if (cellExists(i + 1, j, grid)) {\n if (h <= grid[i + 1][j]) {\n fullS -= h;\n } else {\n fullS -= grid[i + 1][j];\n }\n }\n sum += fullS;\n }\n }\n return sum;\n }\n\n private static boolean cellExists(int row, int col, int[][] array) {\n return (row <= array.length - 1 && row >= 0) && (col <= array[0].length - 1 && col >= 0);\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
surface-area-of-3d-shapes | [Javascript] OVERLAPPING happens in 3 directions! | javascript-overlapping-happens-in-3-dire-ay9t | Since there might be holes in shapes, whose surface areas couldn\'t be projected.\nWe CANNOT use the 2883. Projection Area of 3D Shapes to solve it : (\n.\n\nIn | lynn19950915 | NORMAL | 2022-04-20T06:25:03.487518+00:00 | 2024-04-20T05:15:17.279902+00:00 | 355 | false | Since there might be **holes** in shapes, whose surface areas couldn\'t be projected.\nWe CANNOT use the 2*[883. Projection Area of 3D Shapes](https://leetcode.com/problems/projection-area-of-3d-shapes/) to solve it : (\n.\n\n**Intuition** \n\nWe have to focus on **overlapping** occurrence then.\n\n```\nAssume there are n cubes and k times of overlapping happens\n-> surface area = 6*n-2*k.\n```\n>Note: don\'t forget 3-directions all may overlap.\nA cube of height `h` **has already overlaps`h-1`times ITSELF**!\n\n```\nvar surfaceArea = function(grid) {\n let cube=0, overlap=0;\n for(let i=0; i<grid.length; i++){\n for(let j=0; j<grid[i].length; j++){\n cube+=grid[i][j];\n // x-direction\n if(i>0){overlap+=Math.min(grid[i][j], grid[i-1][j]);}\n // y-direction\n if(j>0){overlap+=Math.min(grid[i][j], grid[i][j-1]);}\n // z-direction\n\t\t\tif(grid[i][j]>1){overlap+=grid[i][j]-1};\n }\n }\n return cube*6-overlap*2;\n};\n```\n\nThanks for your reading and **up-voting** :)\n\n**\u2B50 Check [HERE](https://github.com/Lynn19950915/LeetCode_King) for my full Leetcode Notes ~**\n | 3 | 0 | ['JavaScript'] | 1 |
surface-area-of-3d-shapes | C++ || EASY TO UNDERSTAND | c-easy-to-understand-by-aarindey-yjtb | \nclass Solution {\npublic:\n int surfaceArea(vector<vector<int>>& grid) {\n int ans=0,n=grid.size();\n if(n==1)\n {\n if(grid[0] | aarindey | NORMAL | 2021-12-17T00:57:05.335417+00:00 | 2021-12-17T00:57:05.335446+00:00 | 392 | false | ```\nclass Solution {\npublic:\n int surfaceArea(vector<vector<int>>& grid) {\n int ans=0,n=grid.size();\n if(n==1)\n {\n if(grid[0][0]>0)\n ans+=2;\n ans+=4*grid[0][0];\n return ans;\n }\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<n;j++)\n {\n if(i==0&&j==0||i==n-1&&j==0||i==0&&j==n-1||i==n-1&&j==n-1)\n {\n ans+=2*grid[i][j];\n }\n else if(i==0||j==0||i==n-1||j==n-1)\n {\n ans+=grid[i][j];\n }\n if(grid[i][j]>0)\n ans+=2;\n if(i!=0)\n {\n ans+=abs(grid[i][j]-grid[i-1][j]);\n }\n if(j!=0)\n {\n ans+=abs(grid[i][j]-grid[i][j-1]); \n }\n }\n }\n return ans;\n }\n};\n```\n**Please upvote to motivate me in my quest of documenting all leetcode solutions(to help the community). HAPPY CODING:)\nAny suggestions and improvements are always welcome** | 3 | 1 | ['C'] | 0 |
surface-area-of-3d-shapes | (C++) 892. Surface Area of 3D Shapes | c-892-surface-area-of-3d-shapes-by-qeetc-tqzn | \n\nclass Solution {\npublic:\n int surfaceArea(vector<vector<int>>& grid) {\n int ans = 0, n = grid.size(); \n for (int i = 0; i < n; ++i) {\n | qeetcode | NORMAL | 2021-04-17T04:29:33.584083+00:00 | 2021-04-17T04:29:33.584129+00:00 | 459 | false | \n```\nclass Solution {\npublic:\n int surfaceArea(vector<vector<int>>& grid) {\n int ans = 0, n = grid.size(); \n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < n; ++j) {\n if (grid[i][j]) {\n ans += 4*grid[i][j] + 2; \n if (i) ans -= 2*min(grid[i][j], grid[i-1][j]); \n if (j) ans -= 2*min(grid[i][j], grid[i][j-1]); \n }\n }\n }\n return ans; \n }\n};\n``` | 3 | 0 | ['C'] | 0 |
surface-area-of-3d-shapes | More clear python solution | more-clear-python-solution-by-chinaxuefe-6p0x | python\nclass Solution:\n def surfaceArea(self, grid: List[List[int]]) -> int:\n N = len(grid)\n ret = 0\n for i in range(N):\n | chinaxuefei | NORMAL | 2020-11-10T03:59:06.466715+00:00 | 2020-11-10T03:59:06.466746+00:00 | 398 | false | ```python\nclass Solution:\n def surfaceArea(self, grid: List[List[int]]) -> int:\n N = len(grid)\n ret = 0\n for i in range(N):\n for j in range(N):\n v = grid[i][j]\n if v:\n ret += 2\n ret += v * 4\n if i:\n p = grid[i-1][j]\n ret -= min(v, p) * 2\n if j:\n p = grid[i][j-1]\n ret -= min(v, p) * 2\n return ret\n``` | 3 | 0 | ['Python3'] | 0 |
surface-area-of-3d-shapes | Java solution | java-solution-by-tankztc-qqb9 | \nclass Solution {\n public int surfaceArea(int[][] grid) {\n int area = 0;\n for (int i = 0; i < grid.length; i++) {\n for (int j = | tankztc | NORMAL | 2018-09-25T04:44:43.589309+00:00 | 2018-10-23T14:38:50.230032+00:00 | 476 | false | ```\nclass Solution {\n public int surfaceArea(int[][] grid) {\n int area = 0;\n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid[0].length; j++) {\n if (grid[i][j] != 0) {\n area += grid[i][j] * 4 + 2;\n area -= (i - 1 >= 0) ? Math.min(grid[i][j], grid[i-1][j]) * 2 : 0;\n area -= (j - 1 >= 0) ? Math.min(grid[i][j], grid[i][j-1]) * 2 : 0;\n }\n }\n }\n return area;\n }\n}\n``` | 3 | 0 | [] | 1 |
surface-area-of-3d-shapes | Easy C++ solution || Beginner Friendly | easy-c-solution-beginner-friendly-by-suj-lgyt | 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 | Sujay0_o | NORMAL | 2023-07-02T13:57:09.442977+00:00 | 2023-07-02T13:57:09.443008+00:00 | 1,098 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n^2)\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 {\npublic:\n int surfaceArea(vector<vector<int>>& grid) {\n int ans=0;\n int n=grid.size();\n\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n if(grid[i][j]!=0){\n ans=ans+(grid[i][j]*6 - (grid[i][j]-1)*2);\n }\n if((j+1)<n){\n ans=ans-(min(grid[i][j],grid[i][j+1]));\n }\n if((i+1)<n){\n ans=ans-(min(grid[i][j],grid[i+1][j]));\n }\n if(j!=0){\n ans=ans-(min(grid[i][j],grid[i][j-1]));\n }\n if(i!=0){\n ans=ans-(min(grid[i][j],grid[i-1][j]));\n }\n }\n }\n return ans;\n\n }\n};\n``` | 2 | 0 | ['C++'] | 1 |
surface-area-of-3d-shapes | C++,Logical | clogical-by-nideesh45-9dhw | \nclass Solution {\npublic:\n \n // split the area in different part and find individual ones\n \n int surfaceArea(vector<vector<int>>& grid) {\n | nideesh45 | NORMAL | 2022-07-31T06:30:33.621128+00:00 | 2022-07-31T06:30:33.621174+00:00 | 492 | false | ```\nclass Solution {\npublic:\n \n // split the area in different part and find individual ones\n \n int surfaceArea(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n int bottom_top_area = 2*n*m;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(grid[i][j] == 0) bottom_top_area-=2;\n }\n }\n int eastwest = 0;\n for(int i=0;i<n;i++){\n eastwest+=grid[i][0];\n eastwest+=grid[i][n-1];\n for(int j=0;j<m-1;j++){\n eastwest+=abs(grid[i][j+1]-grid[i][j]);\n }\n }\n int northsouth = 0;\n for(int i=0;i<m;i++){\n northsouth+=grid[0][i];\n northsouth+=grid[m-1][i];\n for(int j=0;j<n-1;j++){\n northsouth+=abs(grid[j+1][i]-grid[j][i]);\n }\n }\n return bottom_top_area+northsouth+eastwest;\n }\n};\n``` | 2 | 0 | ['C'] | 0 |
surface-area-of-3d-shapes | Iterative solution in Python (Reported: 95.28% faster) (Time Complexity O(n^2)) | iterative-solution-in-python-reported-95-m9gw | Report Results\nRuntime: 86 ms, faster than 95.28% of Python3 online submissions for Surface Area of 3D Shapes.\nMemory Usage: 14 MB, less than 24.53% of Python | shaurya-chandhoke | NORMAL | 2022-05-23T06:07:07.157089+00:00 | 2022-05-23T06:08:40.608444+00:00 | 374 | false | #### Report Results\nRuntime: 86 ms, faster than 95.28% of Python3 online submissions for Surface Area of 3D Shapes.\nMemory Usage: 14 MB, less than 24.53% of Python3 online submissions for Surface Area of 3D Shapes.\n\nThis naive implementation favors time over space complexity.\n### Implementation Summary\nFor each `(i,j)`, there are 3 main things to check for:\n1. Is there some `value > 0` at the current cell face? If so, then that means there is also that same value below (Imagine placing a cube on a desk and looking top-down; the surface area at the top-down face should equal the surface area at the bottom face touching the desk). Increment the surface area by 2 unit for each `(i,j)` where this is true (1 for the top-down cell, 1 for the bottom cell).\n2. Is this current cell face located at an edge? If so, the surface area at that edge should equal the face value of the cell (indicating the height of the edge at that grid location)\n\nI used the following perspectives to imagine how this would look like:\n\n**Top Down POV of Grid**\n```\nimagine a person here x [4]\n [2]\n```\n\n**Left Edge POV of Grid**\n```\n[1]\n[1]\n[1][1]\n[1][1] <- block height\n\nx\nsame person here\n```\n\n3. Is there a change in altitude between the current face and the faces directly in **front** and **below** it? If so, include the differences between the two\n\nThis is probably the trickiest because it requires looking ahead if possible. For the purposes of this naive implementation, I employed the following search pattern:\n```\n(i,j)->\n |\n v\n```\n\nOf course, if the current face is at the right-most edge, it won\'t look in front; the same goes if it\'s at the bottom-most edge.\n\nAdding each of these cases to some counter (I called it `surface_area`) will effectively take into account the top face, bottom face, left face, right face, and changes in altitude.\n```python\nclass Solution:\n def surfaceArea(self, grid: List[List[int]]) -> int:\n """\n\t\tNotes\n\t\t============\n\t\t\n Calculations\n ------------\n \n Top and Bottom Face:\n If a positive value exists on the current cell, increment counter (only need to know if it exists, one cell face == 1)\n \n Change in Altitude:\n For each cell, check difference between current position and surrounding\n - Goal is to check diff below current position and in front of current position\n - If at right edge, check below if possible\n - If at bottom edge, check right if possible\n - It not at right and bottom, check both right and bottom\n \n Search Pattern:\n (i,j)->\n |\n v\n\n Left Edge:\n - If at left edge (jth index == 0), increment counter with face value\n \n Right Edge:\n - If at right edge (jth index == (len(n) - 1)), increment counter with face value\n \n Top Edge:\n - If at top edge (ith index == 0), increment counter with face value\n \n Bottom Edge:\n - If at bottom edge (ith index == (len(n) - 1)), increment counter with face value\n \n \n Combining All Calculations Into Single Cycle:\n\n counter = 0\n For i,j:\n counter += topBotFace(i,j) # Gives 2 if face value > 0\n counter += altitude(i,j) # Checks diff\n counter += leftEdge(i,j)\n counter += rightEdge(i,j)\n counter += topEdge(i,j)\n counter += bottomEdge(i,j)\n\n return counter\n """\n surface_area = 0\n n = len(grid)\n\n for i in range(n):\n for j in range(n):\n bottom_edge = False\n right_edge = False\n\n # Top and Bottom Faces\n if grid[i][j] > 0:\n surface_area += 2\n\n # Left edge\n if j == 0:\n surface_area += grid[i][j]\n \n # Right edge\n if j == (n - 1):\n surface_area += grid[i][j]\n right_edge = True\n \n # Top Edge\n if i == 0:\n surface_area += grid[i][j]\n \n # Bottom Edge\n if i == (n - 1):\n surface_area += grid[i][j]\n bottom_edge = True\n \n # Altitude\n surface_area += self.altitude(i, j, grid, right_edge, bottom_edge)\n \n return surface_area\n\n def altitude(self, i, j, grid, right, bot):\n total_diff = 0\n\n if not right and not bot:\n total_diff += abs(grid[i][j] - grid[i][j + 1]) # Look forward\n total_diff += abs(grid[i][j] - grid[i + 1][j]) # Look below\n elif right and not bot:\n total_diff += abs(grid[i][j] - grid[i + 1][j])\n elif bot and not right:\n total_diff += abs(grid[i][j] - grid[i][j + 1])\n else:\n total_diff += 0\n\n return total_diff\n``` | 2 | 0 | ['Iterator', 'Python'] | 0 |
surface-area-of-3d-shapes | Java single pass simple solution | java-single-pass-simple-solution-by-eloh-hs5r | Note how I only check two of the adjacent faces and substract them twice instead of checking the 4 adjacent faces. if it helps please vote up\n```\nclass Soluti | elohimmarron | NORMAL | 2022-03-12T01:01:18.367637+00:00 | 2022-03-12T01:01:18.367666+00:00 | 175 | false | Note how I only check two of the adjacent faces and substract them twice instead of checking the 4 adjacent faces. if it helps please vote up\n```\nclass Solution {\n public int surfaceArea(int[][] grid) {\n int faces = 0; // keeping 2 variables for redability you could add and subtract on each position;\n int adjacent = 0;\n for(int i = 0; i < grid.length; i++){\n for(int j = 0; j < grid[0].length; j++){\n if(grid[i][j] == 0) continue;\n faces += 4 * grid[i][j] + 2;\n if(j + 1 < grid[0].length) adjacent += 2 * Math.min(grid[i][j], grid[i][j + 1]);\n if(i + 1 < grid.length) adjacent += 2 * Math.min(grid[i][j], grid[i + 1][j]);\n }\n }\n return faces - adjacent;\n }\n} | 2 | 0 | [] | 0 |
surface-area-of-3d-shapes | Python 3 : Long Code But Faster And Acceptable | python-3-long-code-but-faster-and-accept-z3gi | Approach: \n1) First we check if there is only one cell in matrix/grid or not.\n If yes then just simply return 6 + 4(the value of cell - 1) : Because 1 cube | deleted_user | NORMAL | 2021-12-04T07:30:07.554643+00:00 | 2021-12-04T12:43:39.105880+00:00 | 266 | false | Approach: \n1) First we check if there is only one cell in matrix/grid or not.\n If yes then just simply return 6 + 4(the value of cell - 1) : Because 1 cube has surface area of 6a^2 i.e. 6 here , everytime a new cube is added at the top of a cube surface area increases by 6-2=4units : as 2 units get glued\n2) If no, then iterate each row and find the difference from the next cell in that row and check if the the cell is not first and last colunm of that row. If it is, then just take the abs difference otherwise add the grid value at that position as we have to cover back side of cells inbetween the first and last row.\n3) Repeat this process with each column.\n4) Finally calculate the top and bottom surfaces if cell is not empty.\n5) Also, add the remaining surfaces of corner cells.\n\n\n```\nclass Solution:\n def surfaceArea(self, grid: List[List[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n if m == n == 1:\n return 6 + 4*(grid[0][0]-1)\n bt = 0\n for i in range(m):\n for j in range(n):\n if grid[i][j]:\n bt += 1\n bt = bt*2\n ans = 0\n for i in range(m):\n for j in range(n-1):\n if j==0:\n ans += abs(grid[i][j]-grid[i][j+1])\n else:\n if i==0 or i==m-1:\n ans += abs(grid[i][j]-grid[i][j+1]) + grid[i][j]\n else:\n ans += abs(grid[i][j]-grid[i][j+1])\n for i in range(n):\n for j in range(m-1):\n if j==0:\n ans += abs(grid[j][i]-grid[j+1][i])\n else:\n if i == 0 or i==n-1:\n ans += abs(grid[j][i]-grid[j+1][i]) + grid[j][i]\n else:\n ans += abs(grid[j][i]-grid[j+1][i])\n ans += 2*(grid[0][0]+ grid[0][n-1] + grid[m-1][0] + grid[m-1][n-1])\n ans += bt\n return ans\n``` | 2 | 0 | ['Math', 'Matrix', 'Python3'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.