title
stringlengths
3
77
title_slug
stringlengths
3
77
question_content
stringlengths
38
1.55k
tag
stringclasses
707 values
level
stringclasses
3 values
question_hints
stringlengths
19
3.98k
view_count
int64
8
630k
vote_count
int64
5
10.4k
content
stringlengths
0
43.9k
__index_level_0__
int64
0
109k
Largest Number After Digit Swaps by Parity
largest-number-after-digit-swaps-by-parity
You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps.
Sorting,Heap (Priority Queue)
Easy
The bigger digit should appear first (more to the left) because it contributes more to the value of the number. Get all the even digits, as well as odd digits. Sort them separately. Reconstruct the number by giving the earlier digits the highest available digit of the same parity.
3,952
25
Since we need the largest number, what we want is basically to have the larger digits upfront and then the smaller ones. But we are given a parity condition that we need to comply to. We are allowed to swap odd digits with odd ones and even with even ones. So we simply maintain two arrays with odd and even digits. The we construct out answer by taking values from the odd or even arrays as per the parity of ith index. \n\n**STEPS**\n1. First make a array with the digits from nums.\n2. Then we traverse through the array and insert odd and even values into `odd` and `even` lists.\n3. We sort these `odd` and `even` lists.\n4. Then traverse from 0 to n, at each step we check for the parity at that index. For even parity we take the largest value from even array and for odd parity we take from odd array. **WE TAKE THE LARGEST VALUE AS A GREEDY CHOICE TO MAKE THE RESULTING NUMBER LARGER.**\n5. Return the result.\n\n**CODE**\n```\nclass Solution:\n def largestInteger(self, num: int):\n n = len(str(num))\n arr = [int(i) for i in str(num)]\n odd, even = [], []\n for i in arr:\n if i % 2 == 0:\n even.append(i)\n else:\n odd.append(i)\n odd.sort()\n even.sort()\n res = 0\n for i in range(n):\n if arr[i] % 2 == 0:\n res = res*10 + even.pop()\n else:\n res = res*10 + odd.pop()\n return res\n```
108,978
Largest Number After Digit Swaps by Parity
largest-number-after-digit-swaps-by-parity
You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps.
Sorting,Heap (Priority Queue)
Easy
The bigger digit should appear first (more to the left) because it contributes more to the value of the number. Get all the even digits, as well as odd digits. Sort them separately. Reconstruct the number by giving the earlier digits the highest available digit of the same parity.
931
7
**Intuition**:\n We can simply `extract the even and odd in different strings and sort them in decreasing order and put them back in main string`.\n **Problem Occurs** : How we will differentiate the even and odd position for puting the odd and even back.\n **Solution**: We will put all even at even element position and all odd at odd element position.\n \n **Algorithm**:\n + Extract \n + sort\n + place them back\n # C++ \n\tint largestInteger(int num) {\n string p= to_string(num) , odd="", even="";\n for(int i=0;i<p.size();i++){\n if((p[i]-\'0\')%2==0) even+= p[i]; else odd+= p[i]; \n\t\t}\n sort(rbegin(odd),rend(odd));\n sort(rbegin(even),rend(even));\n for(int i=0,j=0,k=0;i<p.size();i++) p[i]= (p[i]-\'0\')%2==0? even[j++] : odd[k++];\n return stoi(p);\n }\n**Worst Time** - O( log(num)* log(log(num)) ) ==> For sorting\n**Maximum Space** - O(log(num))
108,981
Largest Number After Digit Swaps by Parity
largest-number-after-digit-swaps-by-parity
You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps.
Sorting,Heap (Priority Queue)
Easy
The bigger digit should appear first (more to the left) because it contributes more to the value of the number. Get all the even digits, as well as odd digits. Sort them separately. Reconstruct the number by giving the earlier digits the highest available digit of the same parity.
894
7
**Approach-**\n* store all digits in an array\n* run two loops and check if the second element is greater than the first and their parity is same or not\n* If yes, we swap the elements.\n* Reconstruct the number using the modified array.\n\n\n```\nclass Solution {\npublic:\n int largestInteger(int num) {\n vector<int>temp;\n int x=num;\n while(x>0){\n int y=x%10;\n temp.push_back(y);\n x=x/10;\n }\n reverse(temp.begin(),temp.end());\n int n=temp.size();\n for(int i=0;i<n;i++){\n int curr=temp[i];\n int p=curr%2;\n int j=i+1;\n while(j<n){\n if(temp[j]>temp[i] and temp[j]%2==p)\n swap(temp[j],temp[i]);\n j++;\n }\n }\n long long int res=0;\n for(int i=0;i<temp.size();i++){\n res+=temp[i];\n res*=10;\n }\n return res/10;\n }\n};\n```
108,983
Largest Number After Digit Swaps by Parity
largest-number-after-digit-swaps-by-parity
You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps.
Sorting,Heap (Priority Queue)
Easy
The bigger digit should appear first (more to the left) because it contributes more to the value of the number. Get all the even digits, as well as odd digits. Sort them separately. Reconstruct the number by giving the earlier digits the highest available digit of the same parity.
212
5
```\nclass Solution {\npublic:\n int largestInteger(int numb) {\n \n int num = numb;\n vector<int> e, o, n;\n while (num) {\n int d = num % 10;\n if (d & 1) o.push_back(d);\n else e.push_back(d);\n num /= 10;\n }\n \n sort(begin(o), end(o), greater<int>());\n sort(begin(e), end(e), greater<int>());\n \n\n int res = 0;\n while (numb) {\n n.push_back(numb%10);\n numb /= 10;\n }\n \n reverse(begin(n), end(n));\n \n int c(0), d(0);\n for (auto i : n) {\n if (i & 1) res = res*10 + o[c++];\n else res = res*10 + e[d++];\n }\n return res;\n }\n};\n```
108,984
Largest Number After Digit Swaps by Parity
largest-number-after-digit-swaps-by-parity
You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps.
Sorting,Heap (Priority Queue)
Easy
The bigger digit should appear first (more to the left) because it contributes more to the value of the number. Get all the even digits, as well as odd digits. Sort them separately. Reconstruct the number by giving the earlier digits the highest available digit of the same parity.
305
6
## ***Please help me to figure it out where i\'m lacking!***\n\n![image]()\n\n\n```\nclass Solution {\npublic:\n int largestInteger(int num) {\n string s = to_string(num);\n int n = s.size();\n priority_queue<int> se,so;\n for(int i=0; i<n; i++)\n {\n if(i%2==0) se.push(s[i]-\'0\');\n else so.push(s[i]-\'0\');\n }\n \n for(int i=0; i<n; i++)\n {\n if(i%2==0){\n int t = se.top() + 48;\n se.pop();\n s[i] = t;\n }\n else{ \n int t = so.top() + 48;\n so.pop();\n s[i] = t;\n }\n }\n return stoi(s);\n }\n};\n```\n\n# **Figured out the mistake....hence adding the correct solution below!**\n\n```\nclass Solution {\npublic:\n int largestInteger(int num) {\n string s = to_string(num);\n int n = s.size();\n priority_queue<int> se,so;\n for(int i=0; i<n; i++)\n {\n if((s[i]-\'0\')%2==0) se.push(s[i]-\'0\');\n else so.push(s[i]-\'0\');\n }\n \n for(int i=0; i<n; i++)\n {\n if((s[i]-\'0\')%2==0){\n int t = se.top() + 48;\n se.pop();\n s[i] = t;\n }\n else{ \n int t = so.top() + 48;\n so.pop();\n s[i] = t;\n }\n }\n return stoi(s);\n }\n};\n```\n\n
108,985
Largest Number After Digit Swaps by Parity
largest-number-after-digit-swaps-by-parity
You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps.
Sorting,Heap (Priority Queue)
Easy
The bigger digit should appear first (more to the left) because it contributes more to the value of the number. Get all the even digits, as well as odd digits. Sort them separately. Reconstruct the number by giving the earlier digits the highest available digit of the same parity.
1,384
15
```\nclass Solution {\n public int largestInteger(int num) {\n PriorityQueue<Integer> opq = new PriorityQueue<>();\n PriorityQueue<Integer> epq = new PriorityQueue<>();\n int bnum = num;\n while(num>0){\n int cur = num%10;\n if(cur%2==1){\n opq.add(cur);\n }else{\n epq.add(cur);\n }\n num /= 10;\n }\n StringBuilder sb = new StringBuilder();\n num = bnum;\n while(num>0){\n int cur = num%10;\n if(cur%2==1)\n sb.insert(0, opq.poll());\n else\n sb.insert(0, epq.poll());\n num /= 10;\n }\n return Integer.parseInt(sb.toString());\n }\n}\n```\n**please leave a like if you found this helpful\nand leave a comment if you have any question\nhappy coding : )**
108,987
Largest Number After Digit Swaps by Parity
largest-number-after-digit-swaps-by-parity
You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps.
Sorting,Heap (Priority Queue)
Easy
The bigger digit should appear first (more to the left) because it contributes more to the value of the number. Get all the even digits, as well as odd digits. Sort them separately. Reconstruct the number by giving the earlier digits the highest available digit of the same parity.
486
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlogn)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass Solution {\npublic:\n int largestInteger(int num) {\n string s = to_string(num);\n string ans;\n int i, j=0, k=0;\n vector<int> even;\n vector<int> odd;\n for(i=0 ; i<s.size() ; i++)\n {\n if((int)s[i]%2==0)\n even.push_back((int)s[i]);\n else\n odd.push_back((int)s[i]);\n }\n\n sort(even.begin(), even.end(), greater<int>());\n sort(odd.begin(), odd.end(), greater<int>());\n\n for(i=0 ; i<s.size() ; i++)\n {\n if((int)s[i]%2==0)\n {\n ans += even[j];\n j++;\n }\n else\n {\n ans += odd[k];\n k++;\n }\n }\n return stoi(ans);\n }\n};\n```\n![upvote new.jpg]()\n
108,991
Largest Number After Digit Swaps by Parity
largest-number-after-digit-swaps-by-parity
You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps.
Sorting,Heap (Priority Queue)
Easy
The bigger digit should appear first (more to the left) because it contributes more to the value of the number. Get all the even digits, as well as odd digits. Sort them separately. Reconstruct the number by giving the earlier digits the highest available digit of the same parity.
1,742
11
**Intuition**\n1. Get frequency of all the digits from 0-9\n2. Construct the newNumber by taking the maximum possible digit for that location => odd/even is determined by the parity of the value in the original number provided\n\n```\n public int largestInteger(int num) {\n char[] nums = Integer.toString(num).toCharArray();\n \n //Calculate the frequency of each digit from 0 - 9\n int[] frequency = new int[10];\n for (int index = 0; index < nums.length; index++) {\n frequency[nums[index] - \'0\']++;\n }\n \n int newNumber = 0;\n int evenIndex = 8; // corresponds to the number 8 \n int oddIndex = 9; // corresponds to the number 9 \n\n // construct the number\n for(int index = 0; index < nums.length; index++) {\n // If the parity of number in current index is even\n if(nums[index] % 2 == 0) {\n // Get first even digit of non-zero frequency\n while(frequency[evenIndex]==0) {\n evenIndex -= 2;\n }\n frequency[evenIndex]--;\n newNumber = newNumber*10 + evenIndex;\n } else {\n // If the parity of number in current index is odd\n // Get first odd digit of non-zero frequency\n while(frequency[oddIndex]==0) {\n oddIndex -= 2;\n }\n frequency[oddIndex]--;\n newNumber = newNumber*10 + oddIndex;\n }\n }\n \n return newNumber;\n }\n```
108,992
Minimize Result by Adding Parentheses to Expression
minimize-result-by-adding-parentheses-to-expression
You are given a 0-indexed string expression of the form "<num1>+<num2>" where <num1> and <num2> represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+'. Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them. The input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.
String,Enumeration
Medium
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
2,251
13
**Approach**\n```\n1. Checking for positions\n"247+38" --> \n 1st-> 24(7+3)8 // one option\n\t\t\t\t\t 2nd-> 24(7+38) // 2nd option\n\t\t\t\t\t 3rd-> 2(47+3)8 //3rd option\n\t\t\t\t\t .... and many like these\n\t\t\t\t\t \n2. calculate value for the left of opening bracket and between\nbrackets and right of closing bracket\n```\n\n\n**CODE**\n```\nclass Solution {\npublic:\n string minimizeResult(string expression) {\n bool plus = false;\n string a = "",b="";\n for(char ch : expression){\n if(ch == \'+\'){\n plus = true;\n }\n if(!plus) a+=ch;\n else b+=ch;\n }\n \n int n = a.length();\n int m = b.length();\n string ans;\n int maxi = INT_MAX;\n for(int i = 0 ; i < n ; i++){\n for(int j = 1 ; j < m ; j++){\n int left;\n if(i==0) left = 1;\n else left = stoi(a.substr(0,i));\n \n int middle = stoi(a.substr(i,n-i))+stoi(b.substr(0,j+1));\n \n int right;\n if(j==m-1)right = 1;\n else right = stoi(b.substr(j+1,m-j-1));\n \n if(left*middle*right < maxi){\n maxi = left*middle*right;\n ans = a.substr(0,i) + "("+ a.substr(i,n-i) + b.substr(0,j+1) + ")" + b.substr(j+1,m-j-1);\n }\n }\n }\n return ans;\n }\n};\n```
109,011
Minimize Result by Adding Parentheses to Expression
minimize-result-by-adding-parentheses-to-expression
You are given a 0-indexed string expression of the form "<num1>+<num2>" where <num1> and <num2> represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+'. Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them. The input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.
String,Enumeration
Medium
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
2,024
21
**Intuition**:\nTry every possible combination and get the answer with minimum answer.\n\n**Explanation**:\n# There will two parts majorly:\n+ 0-index to index having \'+\'\n+ index(\'+\')+1 to last\n\nThe **first part** can be atmost divided into two more subparts while partitioning.\nThe **second part** can be atmost divided into two more subparts while partitioning.\n\nOur outer loop will be from **0** to **index having +**.\nOur inner loop will be from **index having \'+\'** to **n-1**.\n\nSo in this way we will get **4 different set of integers by partitioning** and for **every 4 sets of integers we will find its result** and **we will keep updating two variables having the start index of \'(\' and index of \')\'**.\n\n**Apply Formula between every 4 integer and get one with minimum** : \n>n1 * (n2+n3) * n4 \n\nAt last we will have **our minimum answer in variable** and **position in a and b**.\nWe will just put the brackets at **a** and **b** position.\n\n# C++\n\n string minimizeResult(string exp) {\n int mn= INT_MAX, a=-1,b=-1 ,n= exp.size(), plus=exp.find(\'+\');\n for(int i=0;i<plus;i++){\n for(int j=plus+1;j<n;j++){\n //extract 4 Integers\n int n1= stoi(exp.substr(0,i)==""?"1":exp.substr(0,i)); //from 0 to i index we have one integer\n int n2= stoi(exp.substr(i,plus-i)); //from i to plus-1 index -> we have one integer\n int n3= stoi(exp.substr(plus+1,j-plus)); //from plus+1 index to j , we have one value\n int n4= stoi(exp.substr(j+1)==""?"1":exp.substr(j+1)); //from j to last we have one value\n //update minimum by updating a and b variable\n if(n1*(n2+n3)*n4<mn) mn= n1*(n2+n3)*n4 ,a=i ,b=j+1;\n }\n }\n //insert "(" at a-position and ")" at b-position we captured above\n exp.insert(a,"(");\n if(b==n) exp+=")"; else exp.insert(b+1,")");\n return exp;\n }\n\t\n**Time** - O(n^3)\n**Space** - O(1)
109,012
Minimize Result by Adding Parentheses to Expression
minimize-result-by-adding-parentheses-to-expression
You are given a 0-indexed string expression of the form "<num1>+<num2>" where <num1> and <num2> represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+'. Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them. The input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.
String,Enumeration
Medium
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
4,477
34
```\nclass Solution {\npublic:\n string minimizeResult(string expr) {\n //First find the index of \'+ in expresseion. let it be idx.\n\t\tint idx;\n int n=expr.size();\n for(int i=0;i<n;i++)\n if(expr[i]==\'+\')\n {\n idx=i;\n break;\n }\n\t\t\t\n\t\t//Now find two numbers which are on left and right side of \'+\' sign in expression\t\n string num1 = expr.substr(0,idx);\n string num2 = expr.substr(idx+1,n-idx-1);\n\t\t\n\t\t//b1 and b2 are for brackets . b1=left bracket, b2=right bracket\n int b1=0,b2=0;\n int min =INT_MAX;\n string ans;\n\t\t\n\t\t//p1 and p2 are product number outside the brackets i.e our expresion is p1(sum)p2\n int p1,p2;\n\t\t\n\t\t//Find all possible conditions, iterate left bracket over num1 and right bracket over num2\n for(int b1=0;b1<num1.size();b1++)\n {\n for(int b2=0;b2<num2.size();b2++)\n {\n // s1 and s2 are strings which are outside the left parenthesis and right parenthesis respectively \n string s1=num1.substr(0,b1);\n string s2=num2.substr(b2+1,b2-num2.size()-1);\n \n //if any of the string is empty then its int value should be 1 else its same as string.\n\t\t\t if(s1.empty())\n p1=1;\n else\n p1=stoi(num1.substr(0,b1));\n if(s2.empty())\n p2=1;\n else\n p2=stoi(num2.substr(b2+1,b2-num2.size()-1));\n\t\t\t\t\t\n\t\t\t\t//sum stores the numerical value of the sum between the parenthesis\t\n int sum=stoi(num1.substr(b1,num1.size())) + stoi(num2.substr(0,b2+1));\n //eval stores the numerical value of whole expression\n\t\t\t int eval=p1*sum*p2;\n\t\t\t \n\t\t\t //if velue of expression is less then minimum, then make ans string = s1(sum) s1\n if(eval<min){\n \n min=eval;\n ans=s1+"("+num1.substr(b1,num1.size())+"+"+num2.substr(0,b2+1)+")"+s2;\n \n }\n \n }\n }\n return ans;\n //return final string\n \n }\n};\n```
109,013
Minimize Result by Adding Parentheses to Expression
minimize-result-by-adding-parentheses-to-expression
You are given a 0-indexed string expression of the form "<num1>+<num2>" where <num1> and <num2> represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+'. Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them. The input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.
String,Enumeration
Medium
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
2,370
25
Suppose we have expression "247+38"\nfor this we try to produce every possible string\n\nlike \n1. (247+3)8\n1. (247+38)\n1. 2(47+3)8\n1. 2(47+38)\n1. 24(7+3)8\n1. 24(7+38)\n\nafter generating every possible string ,\nit get converted into 4 differnt numbers\n\n* a-> before the \'(\'\n* b-> after \'(\' before \'+\'\n* c-> after \'+\' before \')\'\n* d-> after \')\'\n\nthen we know our ans will be a*(b+c)*d\n\nbut we know there is one **edge case **\n(247+38) in this a=d=0 , then we have to update a and d value to 1\n\n**Please Upvote the Post**\n\n**JAVA SOLUTION **\n\n```\npublic String minimizeResult(String str) {\n int n=str.length();\n int idx=0;\n while(idx<n && str.charAt(idx)!=\'+\') idx++;\n idx++;\n int ans=1000000000;\n String res="";\n for(int i=0;i<idx-1;i++){\n for(int j=idx;j<n;j++){\n StringBuilder sb=new StringBuilder(str);\n sb.insert(j+1,\')\');\n sb.insert(i,\'(\');\n \n int a=0,b=0,c=0,d=0,k=0;\n for(;sb.charAt(k)!=\'(\';k++){\n a=a*10+(sb.charAt(k)-\'0\');\n }\n k++;\n for(;sb.charAt(k)!=\'+\';k++){\n b=b*10+(sb.charAt(k)-\'0\');\n }\n k++;\n for(;sb.charAt(k)!=\')\';k++){\n c=c*10+(sb.charAt(k)-\'0\');\n }\n k++;\n for(;k<sb.length();k++){\n d=d*10+(sb.charAt(k)-\'0\');\n }\n b=b+c;\n if(a==0) a=1;\n if(d==0) d=1;\n \n int abc=a*b*d;\n if(abc<ans){\n res=sb.toString();\n ans=abc;\n }\n }\n }\n return res;\n }\n```\n\n**C++ SOLUTION**\n```\n\nstring minimizeResult(string str) {\n int n=str.length();\n int idx=0;\n while(idx<n && str[idx]!=\'+\') idx++;\n idx++;\n int ans=1000000000;\n string res="";\n for(int i=0;i<idx-1;i++){\n for(int j=idx;j<n;j++){\n string sb=str.substr(0,i) + "(" + str.substr(i,j+1-i) + ")" +str.substr(j+1,n);\n \n int a=0,b=0,c=0,d=0,k=0;\n for(;sb[k]!=\'(\';k++){\n a=a*10+(sb[k]-\'0\');\n }\n k++;\n for(;sb[k]!=\'+\';k++){\n b=b*10+(sb[k]-\'0\');\n }\n k++;\n for(;sb[k]!=\')\';k++){\n c=c*10+(sb[k]-\'0\');\n }\n k++;\n for(;k<sb.length();k++){\n d=d*10+(sb[k]-\'0\');\n }\n b=b+c;\n if(a==0) a=1;\n if(d==0) d=1;\n \n int abc=a*b*d;\n if(abc<ans){\n res=sb;\n ans=abc;\n }\n }\n }\n return res;\n }\n
109,014
Minimize Result by Adding Parentheses to Expression
minimize-result-by-adding-parentheses-to-expression
You are given a 0-indexed string expression of the form "<num1>+<num2>" where <num1> and <num2> represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+'. Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them. The input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.
String,Enumeration
Medium
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
3,257
23
The code could be simpler, but here we try to limit string operations for efficiency.\n\nThe left side (before plus) and right side of the equation are independent. We can generate all possible pairs of `{mul, sum}` for each side. For example, for `"247+38"`, we will have:\n- Left pairs (`lp`): \n\t- {0, 247} - we will use `1` as multiplier.\n\t- {2, 47}\n\t- {24, 7)\n- Right pairs (`rp`):\n\t- {0, 38} - we will use `1` as multiplier.\n\t- {3, 8}\n\nThen, we will try all combination of those pairs to find the minimum result.\n\n**C++**\n```cpp\nstring minimizeResult(string exp) {\n int plus = exp.find(\'+\');\n vector<int> v;\n vector<pair<int, int>> lp, rp;\n for (int l = stoi(exp.substr(0, plus)), mul = 10; l * 10 >= mul; mul *= 10)\n lp.push_back({ l / mul, l % mul}); \n for (int r = stoi(exp.substr(plus + 1)), mul = 1; r / mul > 0; mul *= 10)\n rp.push_back({ r % mul, r / mul }); \n for (auto [m1, s1] : lp)\n for (auto [m2, s2]: rp)\n if (v.empty() || max(1, m1) * (s1 + s2) * max(1, m2) < max(1, v[0]) * (v[1] + v[2]) * max(1, v[3]))\n v = {m1, s1, s2, m2};\n return (v[0] ? to_string(v[0]) : "") + "(" + to_string(v[1]) \n + "+" + to_string(v[2]) + ")" + (v[3] ? to_string(v[3]) : "");\n}\n```
109,015
Minimize Result by Adding Parentheses to Expression
minimize-result-by-adding-parentheses-to-expression
You are given a 0-indexed string expression of the form "<num1>+<num2>" where <num1> and <num2> represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+'. Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them. The input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.
String,Enumeration
Medium
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
831
7
```\nclass Solution {\npublic:\n int func(string& e,int i,int j,int p){\n int a=1;\n if(i>0) a=stoi(e.substr(0,i));\n int b=stoi(e.substr(i,p-i));\n int c=stoi(e.substr(p+1,j-p));\n int d=1;\n if(j+1<e.size()) d=stoi(e.substr(j+1,e.size()-j));\n return a*(b+c)*d;\n }\n string minimizeResult(string e) {\n int p=0; //will store the index of \'+\'\n for(p=0;p<e.size();p++){\n if(e[p]==\'+\') break;\n }\n int ans=INT_MAX; // will store the minimum possible value\n string res;\n for(int i=0;i<p;i++){ // i-> where we will add \'(\'\n for(int j=p+1;j<e.size();j++){ // j-> where we will add \')\'\n int val=func(e,i,j,p); // try every possible way \n if(val<ans){\n ans=val;\n res=e;\n res.insert(j+1,1,\')\');\n res.insert(i,1,\'(\');\n }\n }\n }\n return res;\n }\n};
109,016
Minimize Result by Adding Parentheses to Expression
minimize-result-by-adding-parentheses-to-expression
You are given a 0-indexed string expression of the form "<num1>+<num2>" where <num1> and <num2> represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+'. Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them. The input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.
String,Enumeration
Medium
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
1,603
18
We have two numbers `left` and `right`.\nAdd Open parenthesis at these poitions for `left` : (0 , left.length()-1)\nAdd Close parenthesis at these poitions for `right` : (1 , right.length()).\n\nFor `left` , multiple will be on the left of the paranthesis and for `right` multiple will be on right.\n\nGet multiple and remaining number for both left and right, and create the final sum.\n\n```\nclass Solution {\n public String minimizeResult(String expression) {\n String[] sp = expression.split("\\\\+");\n String left = sp[0];\n String right = sp[1];\n \n int min = Integer.MAX_VALUE;\n String result = "(" + expression + ")";\n\t\t\n for(int i=0; i<left.length(); i++) { //Index at which we add `(` for left\n int leftMul = left.substring(0, i).equals("") ? 1 : Integer.parseInt(left.substring(0,i));\n int leftNum = Integer.parseInt(left.substring(i));\n \n for(int j=1; j<=right.length(); j++) { //Index at which we add `)` for right\n int rightMul = right.substring(j).equals("") ? 1 : Integer.parseInt(right.substring(j));\n int rightNum = Integer.parseInt(right.substring(0,j));\n \n int sum = leftMul * (leftNum + rightNum) * rightMul;\n if(sum < min) {\n min = sum;\n result = left.substring(0, i) + "(" + left.substring(i) + "+" + right.substring(0, j) + ")" + right.substring(j);\n }\n }\n }\n return result;\n }\n}\n```
109,017
Minimize Result by Adding Parentheses to Expression
minimize-result-by-adding-parentheses-to-expression
You are given a 0-indexed string expression of the form "<num1>+<num2>" where <num1> and <num2> represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+'. Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them. The input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.
String,Enumeration
Medium
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
502
11
Justr try all possibilites before and after \'+\' symbol.\n\neg: expression = "247+38"\n```\n(247+3)8 -> 2000\n(247+38) -> 285\n2(47+3)8 -> 800\n2(47+38) -> 170\n24(7+3)8 -> 1920\n24(7+38) -> 1080\n```\n\n##### C++ Code - 4ms\n```cpp\nstring minimizeResult(string s) {\n int plus = s.find(\'+\');\n\tint minres = INT_MAX, n = s.size();\n string res = "";\n\n for (int i = 0; i < plus; i++) {\n for (int j = plus + 1; j < n; j++) {\n string a = s.substr(0, i);\n string b = s.substr(i, plus - i);\n string c = s.substr(plus + 1, j - plus);\n string d = s.substr(j + 1);\n\n int p = a == "" ? 1 : stoi(a);\n int q = b == "" ? 1 : stoi(b);\n int r = c == "" ? 1 : stoi(c);\n int s = d == "" ? 1 : stoi(d);\n\n int temp = p * (q + r) * s;\n if (temp < minres) {\n minres = temp;\n res = a + "(" + b + "+" + c + ")" + d;\n }\n }\n }\n return res;\n}\n```
109,018
Minimize Result by Adding Parentheses to Expression
minimize-result-by-adding-parentheses-to-expression
You are given a 0-indexed string expression of the form "<num1>+<num2>" where <num1> and <num2> represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+'. Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them. The input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.
String,Enumeration
Medium
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
2,609
16
*Since the given maximum size is only 10, we can easily cover all possible options without TLE. Thus we use 2 pointers to cover all options.*\n\n**STEPS**\n1. Traverse two pointers `l` & `r`. **L** pointer goes from 0 to **plus_index** and **R** pointer goes from **plus_index+1** to **N**. **plus_index** is the index of \'+\' in the expression. The **L** pointer is the position of \'(\' and **R** is for \')\'.\n2. Use f string formatting to generate a expression. \n3. Use evaulate function to get the result of the following expression.\n4. If the new result is better than the old one, then update otherwise continue.\n \n**NOTE** \n\u27A1\uFE0F**The `evaluate` function basically converts "23(44+91)2" into "23 X (44+91) X 2" without ever having any * sign in the edges(used strip methods for that). `eval()` is a library function that evaluates a mathematical expression given in string form.**\n\u27A1\uFE0F **`ans` is a list of 2 values, first is the smalles result of any expression and second is the expression itself.**\n\n**CODE**\n```\nclass Solution:\n def minimizeResult(self, expression: str) -> str:\n plus_index, n, ans = expression.find(\'+\'), len(expression), [float(inf),expression] \n def evaluate(exps: str):\n return eval(exps.replace(\'(\',\'*(\').replace(\')\', \')*\').lstrip(\'*\').rstrip(\'*\'))\n for l in range(plus_index):\n for r in range(plus_index+1, n):\n exps = f\'{expression[:l]}({expression[l:plus_index]}+{expression[plus_index+1:r+1]}){expression[r+1:n]}\'\n res = evaluate(exps)\n if ans[0] > res:\n ans[0], ans[1] = res, exps\n return ans[1]\n```
109,019
Minimize Result by Adding Parentheses to Expression
minimize-result-by-adding-parentheses-to-expression
You are given a 0-indexed string expression of the form "<num1>+<num2>" where <num1> and <num2> represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+'. Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them. The input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.
String,Enumeration
Medium
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
1,270
5
```\nclass Solution:\n def minimizeResult(self, expression: str) -> str: # Example: "247+38" \n # left, right = "247","38"\n left, right = expression.split(\'+\') \n value = lambda s:eval(s.replace(\'(\',\'*(\').replace(\')\',\')*\').strip(\'*\')) \n \n lft = [ left[0:i]+\'(\'+ left[i:] for i in range( len(left ) )] # lft = [\'(247\', \'2(47\', \'24(7\']\n rgt = [right[0:i]+\')\'+right[i:] for i in range(1,len(right)+1)] # rgt = [\'3)8\', \'38)\']\n \n return min([l+\'+\'+r for l in lft for r in rgt], key = value) # = min[(247+3)8,(247+38),2(47+3)8,2(47+38),24(7+3)8,24(7+38)]\n # | | | | | | \n # 2000 285 800 170 1920 1080 \n # |\n # return 2(47+38)\n\n```\n[](http://)\n\nI could be wrong, but I think time complexity is *O*(*N*^2) and space complexity is *O*(*N*).
109,022
Minimize Result by Adding Parentheses to Expression
minimize-result-by-adding-parentheses-to-expression
You are given a 0-indexed string expression of the form "<num1>+<num2>" where <num1> and <num2> represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+'. Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them. The input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.
String,Enumeration
Medium
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
671
8
Break the expresion into four numbers like **expresion = first + second**. Then break both left and right into two numbers: **first = num1, num2** and **second = num 3 and num 4**. Calculate the result with of these four numbers with the equation: **num1(num2 + num3)num4** , and keep track of the minimal result. Once a minimal found, update the result\n\n\n```\nclass Solution(object):\n def minimizeResult(self, expression):\n """\n :type expression: str\n :rtype: str\n """\n first, second = expression.split(\'+\')\n score = float(\'inf\')\n res = \'\'\n for i in range(len(first)):\n num_1 = int(first[:i]) if i != 0 else 1\n num_2 = int(first[i:])\n for j in range(1, len(second) + 1):\n num_3 = int(second[:j])\n num_4 = int(second[j:]) if j != len(second) else 1\n cur_score = num_1*(num_2 + num_3)*num_4\n if cur_score < score:\n res = first[:i] + \'(\' + first[i:] + \'+\' + second[:j] + \')\' + second[j:]\n score = cur_score\n\n return res\n```
109,026
Maximum Product After K Increments
maximum-product-after-k-increments
You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo.
Array,Greedy,Heap (Priority Queue)
Medium
If you can increment only once, which number should you increment? We should always prioritize the smallest number. What kind of data structure could we use? Use a min heap to hold all the numbers. Each time we do an operation, replace the top of the heap x by x + 1.
84
7
\uD83D\uDCAF\uD83D\uDD25 C++ | Java || Python || JavaScript \uD83D\uDCAF\uD83D\uDD25\n\n***Read Whole article :*** \n\nVideo : \n\nAppraoch : min Heap / priority queue\n\nViuslizationn\n![image]()\n\n![image]()\n\n\n***Read Whole article :***
109,059
Maximum Product After K Increments
maximum-product-after-k-increments
You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo.
Array,Greedy,Heap (Priority Queue)
Medium
If you can increment only once, which number should you increment? We should always prioritize the smallest number. What kind of data structure could we use? Use a min heap to hold all the numbers. Each time we do an operation, replace the top of the heap x by x + 1.
2,718
122
<br/> We can increment minimum number in all k operations and take their product in end.\n\n**But why it works ?**\n \nLet\'s take two integers **x and y and (x > y)**\n\nNow if you **increment x by 1** then your product will be\nproduct = (x + 1) * y = **x * y + y**\n\nAnd if you **increment y by 1** then your product will be\nproduct = x * (y + 1) = **x * y + x**\n\nAs x * y is common in both, and **as x > y so (x * y + x > x * y + y)**\nThat\'s why it\'s always optimal to increment minimum number if you want to maximize their product\n\nSo, we do this for all k operations.\n<br/>\n\n**C++ Code:**\n\n```\nclass Solution {\npublic:\n int maximumProduct(vector<int>& nums, int k) {\n \n priority_queue<int, vector<int>, greater<int>> pq(nums.begin(), nums.end());\n \n while(k--) {\n int mini = pq.top();\n pq.pop();\n pq.push(mini + 1);\n }\n \n long long ans = 1, mod = 1e9+7;\n \n while(!pq.empty()) {\n ans = ((ans % mod) * (pq.top() % mod)) % mod;\n pq.pop();\n }\n \n return (int)ans;\n }\n};\n```\n\n<br/>
109,064
Maximum Product After K Increments
maximum-product-after-k-increments
You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo.
Array,Greedy,Heap (Priority Queue)
Medium
If you can increment only once, which number should you increment? We should always prioritize the smallest number. What kind of data structure could we use? Use a min heap to hold all the numbers. Each time we do an operation, replace the top of the heap x by x + 1.
4,392
53
Product of the array will be maximum when the smallest number in the array is maximum.\nWe use priority queue to find the smallest element in every iteration and increase it by 1.\n\n**Approach-**\n**Insert all elements into min heap.\nRun a loop K times and find the smallest element and increment it by 1.\nPop the elements and find the product**\n\n```\nclass Solution {\npublic:\n int maximumProduct(vector<int>& nums, int k) {\n int mod=pow(10,9)+7;\n priority_queue <int, vector<int>, greater<int>> pq;\n for(int i=0;i<nums.size();i++){\n pq.push(nums[i]);\n }\n while(k>0){\n int x=pq.top();\n pq.pop();\n x=x+1;\n pq.push(x);\n k--;\n }\n long long int ans=1;\n while(pq.size()>0){\n int x=pq.top();\n pq.pop();\n ans=(ans*x)%mod;\n }\n return ans;\n }\n};\n```
109,065
Maximum Product After K Increments
maximum-product-after-k-increments
You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo.
Array,Greedy,Heap (Priority Queue)
Medium
If you can increment only once, which number should you increment? We should always prioritize the smallest number. What kind of data structure could we use? Use a min heap to hold all the numbers. Each time we do an operation, replace the top of the heap x by x + 1.
2,568
26
Key Points\nwe tried to add k to numbers in such a way that the possible differnce between them is minimum\nBut why so ?\nbecause suppose we have 2 numbers 1 , 1 and k=7\nthen we can do\n1. a=1+1, b=1+6 (2*7)=14\n1. a=1+2, b=1+5 (3*6)=18\n1. a=1+3, b=1+4 (4*5)=20\nso by minimising the diff we get the maximum possible product.\n\nProof\nLets consider 3 integers x, y, z. Where x<y<z. Now we need to add 1 to any of these integers and find which integers increment will lead to maximum product.\n```\nx incremented\ty incremented\tz incremented\n(x+1)*y*z\tx*(y+1)*z\tx*y*(z+1)\nxyz + yz\txyz + xz\txyz + xy\n```\n\n\nxyz is common in all of the three cases and yz(additional factor) will lead to maximum product. Incrementing least number in the array will always have additional factor which will consists of products of all integers except the smallest one. If we increment any-other number the smallest number will be included in the additional factor and the incremented number is excluded. Thus the prior case always leads to maximum product\n\nSo how we achieve this by writng code ??\nwe have to extract minimum say **num1** and 2nd minimum say **num2** for that i am using priority queue\nonce we extract i have to add **Math.min(k,(num2-num1)+1)** in our minimum and **subtract same from the k**\ndo the till the value of k is not become 0\n\nNow question may be arises why Math.min(k,(num2-num1)+1) ?\nANS-> because we have to add the diff between the min and 2 min, instead of adding 1 every time,\nIt will reduce time complexity.\n\nSuppose we have arr=[1,10^5], k=10^5\nin this case The TC of my code will be O(1)\nbut if we add 1 every time Then The TC will become 10^5;\n\n**Please Upvote The solution**\n\n**C++ Soltuion**\n\t\n\t```\n\tint maximumProduct(vector<int>& nums, int k) {\n priority_queue<int, vector<int>, greater<int>> pq;\n long long ans=1, MOD = 1e9+7;\n if(nums.size()==1){\n ans=(k+nums[0])%MOD;\n return ans;\n }\n for(auto ele:nums) pq.push(ele);\n while(k) {\n int x = pq.top(); pq.pop();\n int y=pq.top(); pq.pop();\n int diff=min(k,y-x+1);\n x+=diff;\n k-=diff;\n pq.push(x);\n pq.push(y);\n }\n while(!pq.empty()) {\n int x = pq.top(); pq.pop();\n ans = (ans*x)%MOD;\n }\n return ans;\n }\n\t```\n\t\n**Java Solution**\n```\npublic int maximumProduct(int[] nums, int k) {\n int n=nums.length;\n long mod=1000000007;\n if(n==1){\n long ans=(nums[0]+k)%mod;\n return (int)ans;\n }\n PriorityQueue<Long> pq=new PriorityQueue<>();\n for(int a:nums){\n pq.add((long)a);\n }\n while(k>0){\n long num1=pq.remove();\n long num2=pq.remove();\n long diff=Math.min(k,(num2-num1)+1);\n num1+=diff;\n k-=diff;\n pq.add(num1);\n pq.add(num2);\n }\n long ans=1;\n while(!pq.isEmpty()){\n ans=(ans*pq.remove())%mod;\n }\n return (int)ans;\n }\n```
109,067
Maximum Product After K Increments
maximum-product-after-k-increments
You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo.
Array,Greedy,Heap (Priority Queue)
Medium
If you can increment only once, which number should you increment? We should always prioritize the smallest number. What kind of data structure could we use? Use a min heap to hold all the numbers. Each time we do an operation, replace the top of the heap x by x + 1.
2,095
18
```\nimport heapq\n\nclass Solution:\n def maximumProduct(self, nums, k: int) -> int:\n \n # creating a heap\n heap = []\n for i in nums:\n heapq.heappush (heap,i)\n \n \n # basic idea here is keep on incrementing smallest number, then only multiplication of that number will be greater\n # so basically till I have operations left I will increment my smallest number\n while k :\n current = heapq.heappop(heap)\n heapq.heappush(heap, current+1)\n k-=1\n \n result =1\n \n # Just Multiply all the numbers in heap and return the value\n while len(heap)>0:\n x= heapq.heappop(heap)\n result =(result*x )% (10**9+7)\n \n return result\n```
109,068
Maximum Product After K Increments
maximum-product-after-k-increments
You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo.
Array,Greedy,Heap (Priority Queue)
Medium
If you can increment only once, which number should you increment? We should always prioritize the smallest number. What kind of data structure could we use? Use a min heap to hold all the numbers. Each time we do an operation, replace the top of the heap x by x + 1.
1,805
21
**Intuition:** to get the largest product, we should increment the smallest number so far.\n\n**C++**\n```cpp\nint maximumProduct(vector<int>& nums, int k) {\n make_heap(begin(nums), end(nums), greater<int>());\n while (k--) {\n pop_heap(begin(nums), end(nums), greater<int>());\n ++nums.back();\n push_heap(begin(nums), end(nums), greater<int>()); \n }\n return accumulate(begin(nums), end(nums), 1LL, [](long long res, int n) { return res * n % 1000000007; });\n}\n```
109,071
Maximum Product After K Increments
maximum-product-after-k-increments
You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo.
Array,Greedy,Heap (Priority Queue)
Medium
If you can increment only once, which number should you increment? We should always prioritize the smallest number. What kind of data structure could we use? Use a min heap to hold all the numbers. Each time we do an operation, replace the top of the heap x by x + 1.
792
7
```\nMOD = 10 ** 9 + 7\n\nclass Solution:\n def maximumProduct(self, nums: list[int], k: int) -> int:\n nums.sort()\n def get_index():\n for i, n in enumerate(accumulate(nums)):\n if (i + 1) * nums[i] - n >= k:\n return i\n return len(nums)\n idx = get_index() - 1\n q, r = divmod(k + sum(nums[:idx + 1]), idx + 1)\n return (pow(q + 1, r, MOD) * pow(q, idx + 1 - r, MOD) * prod(nums[idx + 1:])) % MOD\n```\n\nNo heap used.\nTime complexity: O(N log N) (doesn\'t depend on `k`)
109,072
Maximum Product After K Increments
maximum-product-after-k-increments
You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo.
Array,Greedy,Heap (Priority Queue)
Medium
If you can increment only once, which number should you increment? We should always prioritize the smallest number. What kind of data structure could we use? Use a min heap to hold all the numbers. Each time we do an operation, replace the top of the heap x by x + 1.
1,429
14
***Intuition : To get the largest product we need to increment the smallest number we have. To get the smallest number always min heap can be used.***\n\n**Approach: The task can be solved with the help of min-heap.**\n\n1. Insert all the elements inside a min-heap\n1. Pop the top element from the min-heap, and increment it by 1 , also decrement K\n1. Insert the popped element back to min-heap\n1. Continue this process till k > 0\n**The maximum product will be the product of all the elements inside the min-heap**\n\n**TC: O(klogn)**\n**SC: O(n)**\n\n```\nclass Solution {\npublic:\n int maximumProduct(vector<int>& nums, int k) {\n \n priority_queue <int, vector<int>, greater<int>> pq;\n for (auto& num : nums) pq.push(num);\n \n while (k--) {\n int top = pq.top();\n\t\t\tpq.pop();\n pq.push(top+1);\n }\n \n long long res(1), mod(1e9+7);\n while (!pq.empty()) {\n res = (res*pq.top()) % mod;\n pq.pop();\n }\n return (int)res;\n }\n};\n```\n\n**Java**\n\n```\nclass Solution {\n public int maximumProduct(int[] nums, int k) {\n \n Queue<Integer> pq = new PriorityQueue<>();\n for (int num : nums) pq.add(num);\n \n while (k-->0) {\n int top = pq.poll() + 1 ;\n pq.add(top);\n }\n\n long res = 1;\n while (!pq.isEmpty()) {\n res = (res*pq.poll()) % 1000000007;\n }\n\n return (int)(res);\n }\n}\n```
109,073
Maximum Product After K Increments
maximum-product-after-k-increments
You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo.
Array,Greedy,Heap (Priority Queue)
Medium
If you can increment only once, which number should you increment? We should always prioritize the smallest number. What kind of data structure could we use? Use a min heap to hold all the numbers. Each time we do an operation, replace the top of the heap x by x + 1.
350
6
Using the binary search, we are trying to find a number **x** upto which every number of the array can be raised ( if they are smaller than **x** ) using atmost **k** operations. And we need to find the maximum **x** using binary search and suppose this max value is **x_max**. The only thing we need to care about is that even after making all elements\' min value to **x_max**, **k** may not be zero and still we can use some more operations. So, in the **isValid()** function, if the **mid** is reachable then I am immediately finding the product using **full k** and updating the ans. The code is given below:\n\n```\n#define mod 1000000007\n\nclass Solution {\npublic:\n int maximumProduct(vector<int>& nums, int k) {\n int n= nums.size(), s= 0, e= 1e7;\n \n long long int ans=0;\n while(s<=e){\n int mid= (e-s)/2+s;\n if(isValid(mid, nums, k, ans)){ \n s= mid+1;\n }else{\n e= mid-1;\n }\n }\n return (int)ans;\n }\n \n bool isValid(int mid, vector<int>&nums, int k, long long int &ans){\n for(int x: nums){\n k-= max(0, mid-x);\n if(k<0)\n return false;\n }\n long long int prod=1;\n for(int x: nums){\n int temp;\n if(x<=mid){\n if(k>0){\n temp= mid+1;\n k--;\n }else{\n temp= mid;\n }\n }else{\n temp= x;\n }\n prod= mul(prod, temp);\n }\n ans= prod;\n return true;\n }\n \n long long int mul(long long int x,long long int y){\n return ((x%mod)*(y%mod))%mod;\n }\n};\n```\n
109,074
Maximum Product After K Increments
maximum-product-after-k-increments
You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo.
Array,Greedy,Heap (Priority Queue)
Medium
If you can increment only once, which number should you increment? We should always prioritize the smallest number. What kind of data structure could we use? Use a min heap to hold all the numbers. Each time we do an operation, replace the top of the heap x by x + 1.
281
5
Think about a simple case, assume you have **[4, 1]**.\nThe current product is **4 * 1 = 4**.\n1. If we increment the **4**, the array will be **[5, 1]** and the result will be **5**. \u274C\n2. If we increment **1**, the array will be **[4, 2**] and the result will be **8**. \u2705\nOption 2 wins.\n\nThe current product after update is **4 * 2 = 8**.\n1. If we increment the **4**, the array will be **[5, 2]** and the result will be **10**. \u274C\n2. If we increment the **2**, the array will be **[4, 3]** and the result will be **12**. \u2705\nOption 2 wins. And so on ...\n\nIf you notice it, what\'s actually happening with each increment is that we are **adding the other number in the array to the current product**.\n\nYou\'re basically adding `1`, and this `1` is multiplied by all numbers other than the number you\'ve added this `1` to. The result of the multiplication is added to the current product.\nIn the above example, the array had only two elements, that\'s why we are always adding the other element to the current product.\n\nIf the array is for example [6, 5, 3], the current product is 6 * 5 * 3 = 90, updating the array by adding 1 to 3 is just as simple as adding all other numbers\' product (6 * 5) to current product (90), i.e., the result becomes 120.\n\nThat\'s why the solution is to always increment the minimum of the array. This ensures that the product of all other numbers except the minimum is max.\nA min heap is the easiest way to track the minimum.\n\n**C++ Code:**\n```\n#define MOD 1000000007\n\nclass Solution {\npublic:\n int maximumProduct(vector<int>& nums, int k) {\n priority_queue<int, vector<int>, greater<int>> min_heap(nums.cbegin(), nums.cend());\n while(k--){\n int min_elem = min_heap.top();\n min_heap.pop();\n min_heap.push(min_elem + 1);\n }\n long result = 1;\n while(!min_heap.empty()){\n result *= min_heap.top();\n result %= MOD;\n min_heap.pop();\n }\n return result;\n }\n};\n```
109,078
Maximum Product After K Increments
maximum-product-after-k-increments
You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo.
Array,Greedy,Heap (Priority Queue)
Medium
If you can increment only once, which number should you increment? We should always prioritize the smallest number. What kind of data structure could we use? Use a min heap to hold all the numbers. Each time we do an operation, replace the top of the heap x by x + 1.
912
11
# **Explanation**\nBuild up the binary heap.\nPop, increment and push for `k` times.\n<br>\n\n# **Complexity**\nHeapify `O(n)` to build up a binary heap\nTime `O(KlogN)`, `pop` and `push` take `O(logn)` time.\nSpace `O(n)` for the heap, reuse the input here.\n<br>\n\n\n**Python**\n```py\n def maximumProduct(self, A, k):\n heapify(A)\n for i in range(k):\n heappush(A, heappop(A) + 1)\n return reduce(lambda p, a: p * a % (10**9 + 7), A, 1)\n```\n
109,079
Maximum Product After K Increments
maximum-product-after-k-increments
You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo.
Array,Greedy,Heap (Priority Queue)
Medium
If you can increment only once, which number should you increment? We should always prioritize the smallest number. What kind of data structure could we use? Use a min heap to hold all the numbers. Each time we do an operation, replace the top of the heap x by x + 1.
418
6
**Approach:** The approach is to increase the total product by increasing the smallest element in the array by one (do this k times to the smallest element). \nWhy the smallest element? For example: [1,5,2] and k=1. If we increase 5 by 1, our product will be 12. But, if we increase 1 by 1, our prodcut will be 5* 2* 2=20. \n\n**Data Structure:** Min-heap would be the best as we need to keep track of the smallest element after each updation. \n\n```\nclass Solution {\npublic:\n int maximumProduct(vector<int>& nums, int k) {\n priority_queue <int, vector<int>, greater<int> > pq;\n for(int n:nums){\n pq.push(n);\n }\n long int mod=1000000007,i=0,ans=1;\n while(i<k){\n int m=pq.top();\n pq.pop();\n pq.push(m+1);\n i++;\n }\n while(pq.size()){\n ans=(ans*pq.top())%mod;\n pq.pop();\n }\n return ans%mod;\n }\n};\n```
109,086
Maximum Product After K Increments
maximum-product-after-k-increments
You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo.
Array,Greedy,Heap (Priority Queue)
Medium
If you can increment only once, which number should you increment? We should always prioritize the smallest number. What kind of data structure could we use? Use a min heap to hold all the numbers. Each time we do an operation, replace the top of the heap x by x + 1.
382
7
See my latest update in repo [LeetCode]()\n## Solution 1. Heap\n\n```cpp\n// OJ: \n// Author: github.com/lzl124631x\n// Time: O(NlogN)\n// Space: O(N)\nclass Solution {\npublic:\n int maximumProduct(vector<int>& A, int k) {\n long mod = 1e9 + 7, ans = 1;\n priority_queue<int, vector<int>, greater<>> pq(begin(A), end(A));\n while (k--) {\n int u = pq.top(), d = 1;\n pq.pop();\n pq.push(u + 1);\n }\n while (pq.size()) {\n ans = ans * pq.top() % mod;\n pq.pop();\n }\n return ans;\n }\n};\n```\n\n## Solution 2. Binary Search\n\n```cpp\n// OJ: \n// Author: github.com/lzl124631x\n// Time: O(NlogN)\n// Space: O(1)\nclass Solution {\npublic:\n int maximumProduct(vector<int>& A, int k) {\n long mod = 1e9 + 7, ans = 1, L = 0, R = LONG_MAX, r = 0;\n sort(begin(A), end(A));\n while (L <= R) { // After the binary search, R is the maximum number such that if we turn all A[i] < R to R, we take no more than `k` increments\n long M = L + (R - L) / 2, used = 0;\n for (int n : A) {\n used += max(0L, M - n);\n if (used > k) break;\n }\n if (used <= k) {\n L = M + 1;\n r = k - used; // `r` is the remainder increments\n } else R = M - 1;\n }\n for (int n : A) {\n int diff = min((long)k, max(0L, R - n));\n if (r) diff++, r--;\n k -= diff;\n ans = ans * (n + diff) % mod;\n }\n return ans;\n }\n};\n```\n\n## Solution 3. Greedy\n\n```cpp\n// OJ: \n// Author: github.com/lzl124631x\n// Time: O(NlogN)\n// Space: O(1)\nclass Solution {\n void fillK(vector<int> &A, int k) {\n long N = A.size(), sum = 0, i = 0; \n while (i < N && A[i] * i - sum <= k) sum += A[i++]; // If we bump `A[0]~A[i-1]` to be `A[i]`, we need `A[i] * i - (A[0]+...+A[i-1])` increments which should be no more than `k`\n int h = (sum + k) / i, r = (sum + k) % i; // We split `sum + k` heights among `A[0]~A[i-1]` `i` elements.\n for (int j = 0; j < i; ++j) {\n A[j] = h; \n if (j < r) A[j]++;\n }\n }\npublic:\n int maximumProduct(vector<int>& A, int k) {\n long mod = 1e9 + 7, ans = 1;\n sort(begin(A), end(A));\n fillK(A, k);\n for (int n : A) ans = ans * n % mod;\n return ans;\n }\n};\n```
109,092
Maximum Product After K Increments
maximum-product-after-k-increments
You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo.
Array,Greedy,Heap (Priority Queue)
Medium
If you can increment only once, which number should you increment? We should always prioritize the smallest number. What kind of data structure could we use? Use a min heap to hold all the numbers. Each time we do an operation, replace the top of the heap x by x + 1.
421
9
We have to always increment the smallest element of the array to get the maximun product.\n\nWe create an array buckets which is of size max(nums). We use this array to keep track of the number of times each element is repeated.\nWe also keep track of the smallest element of the array. \nIf i is the smallest element of the array, we decrement buckets[i] by one and increment buckets[i+1] by 1 (k times). The value of the smallest element may change on every iteration so we may have to update the smallest element after performing the above operation.\nAfter we have done this k times, we have to multiply the numbers to get the product by referring the buckets array (to check how many times each number is repeated).\n\nEdge case: When the smallest number becomes equal to the largest number and we have still not performed k operations.\n\nExample:\narray = [0, 4]; k = 7\n\nIndex &nbsp;&nbsp;&nbsp;: &nbsp;0 1 2 3 4\nBuckets: [1,0,0,0,1]\nSmallest element = 0\nk = 7\n\n1st iteration:\nWe decrement the first index and increment the second index.\nIndex &nbsp;&nbsp;&nbsp;: &nbsp;0 1 2 3 4\nBuckets: [0,1,0,0,1]\nSmallest element = 1\nk = 6 (We have to increment numbers 6 more times now)\n\nAfter performing 3 more iterations the same way, we get the following:\nIndex &nbsp;&nbsp;&nbsp;: &nbsp;0 1 2 3 4\nBuckets: [0,0,0,0,2]\nSmallest element = 4\nk = 3\n\nIf k was equal to 0, we could stop here and multiply 4*4 to get the answer as 16.\nThis is the edge case as k is still greater than 0 and we cannot update the smallest element in buckets anymore as the index of buckets will be out of bounds.\n\nHow to resolve this:\nSince k is greater than the length of the input array, we will have to increment all the elements of the array (k / length) times. After this there might be (k % length) elements that would still have to be incremented, so we have to increment those as well.\n\nContinuing the example:\nCurrent array: [4, 4]\nSmallest element = 4\nk = 3\n\nIncrement all elements by: x = (3 / 2) = 1 time(s)\nAfter incrementing all elements x times, we need to increment (3 % 2 = 1) element(s) one time.\nImplementing the above 2 lines we get the array as: [5, 6]\nTherefore the answer we get is: 5 * 6 = 30\n\nTime and Space Complexity: O(m), where m is the largest element of the array\n\n```\n def maximumProduct(self, nums: List[int], k: int) -> int:\n maxi = max(nums)\n mini = min(nums)\n buckets = [0] * (maxi + 1)\n mod = 10 ** 9 + 7\n \n\t\t# Adding all the numbers in the buckets array\n for n in nums:\n buckets[n] += 1\n \n for i in range(k):\n\t\t\t# If mini becomes equal to maxi, then we wont be able to update the buckets array so we break out of the loop\n if mini + 1 == len(buckets): break\n \n buckets[mini] -= 1\n buckets[mini+1] += 1\n\t\t\t# If we have exhausted the minimum element, then we go to the next element\n if buckets[mini] == 0: mini += 1\n k -= 1\n \n ans = 1\n if k > 0:\n\t\t\t# If k is less than len, then x will be zero\n x = k // len(nums)\n k %= len(nums)\n mini += x\n mtimes = len(nums) - k\n nextt = mini + 1\n for i in range(mtimes):\n ans = (ans * mini) % mod\n for i in range(k):\n ans = (ans * nextt) % mod\n\n else:\n for i in range(mini, len(buckets)):\n while buckets[i]:\n ans = (ans * i) % mod\n buckets[i] -= 1\n \n return ans\n```
109,093
Maximum Total Beauty of the Gardens
maximum-total-beauty-of-the-gardens
Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a 0-indexed integer array flowers of size n, where flowers[i] is the number of flowers already planted in the ith garden. Flowers that are already planted cannot be removed. You are then given another integer newFlowers, which is the maximum number of flowers that Alice can additionally plant. You are also given the integers target, full, and partial. A garden is considered complete if it has at least target flowers. The total beauty of the gardens is then determined as the sum of the following: Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers.
Array,Two Pointers,Binary Search,Greedy,Sorting
Hard
Say we choose k gardens to be complete, is there an optimal way of choosing which gardens to plant more flowers to achieve this? For a given k, we should greedily fill-up the k gardens with the most flowers planted already. This gives us the most remaining flowers to fill up the other gardens. After sorting flowers, we can thus try every possible k and what is left is to find the highest minimum flowers we can obtain by planting the remaining flowers in the other gardens. To find the highest minimum in the other gardens, we can use binary search to find the most optimal way of planting.
8,680
198
Its clear that if we have more complete gardens, we are likely to have fewer flowers in the smallest garden. We are not sure how many complete gardens we need to maximize the score, hence we will try every possible number of complete garden. \n\nWe want to use fewer flowers to fill a complete garden, hence, sort gardens by the number of flowers and complete each garden from the incomplete garden that having the most flowers. \n\nTherefore we will \n- **count complete gardens from tail**\n- **maximize the incomoplete garden from head**.\n\nNotice that we have at most `new` flowers to plant, if we make all the gardens after `j` complete, the remaining flowers equals `new` minus the cost to make these gardens complete.\n\nThen we maximize the number of flowers using the updated `new`, as shown in the picture below. Hence, we have the score in this case.\n\n![image]()\n\n\nThen we move on to make one more complete garden, that is, to make `j-1 -th` garden as complete. If there is still flowers left after making this garden complete, we will repeat the same process to calculate the maximum minimum number of flowers.\n\n![image]()\n\nHow to calculate the maximum incomplete flower?\n\nRecall that we split the problem into two halves, getting the cost to complete gardens after `j` is straigtforward, we just need to iterate from `n-1` to `j` and calculate the cost.\n\n![image]()\n\nFor the second half: **maximize the incomplete flowers**, we can build an auxiliary list `cost`, as shown in the picture below. Basically, `cost[i]` stands for the total cost to make all the gardens before `i` having the same number of flowers as `garden i\'s`. \nFor instance, I colored the `cost[1]` in purple and you can tell the reason why `cost[1] = 2`.\n\n![image]()\n\nSuppose we have 6 flowers and would like to maximize the incomplete flowers. \n- Find how many gardens will be planted using binary search. If `new` is no less than `cost[i]`, meaning we can make all the first `i` gardens having `A[i]` flowers.\n- Check if we can increase the number of flowers in all the `i` gardens any more.\n\nMore details:\n\n![image]()\n\n> In case I didn\'t explain it well, take a look at the right hand side of the picture above. What does the `idx=3` of the binary search tell? It means that the `new=6` we have is enough to make `3` gardens having the same number of flowers\n\n**Steps**\n> In short, we will stop by every incomplete garden (by decreasing order), for each garden:\n> - Maximize the smallest incomplete garden.\n> - Get the current score and update the maximum score.\n> - Make this garden complete, if possible and move on to the next incomplete garden.\n\n**Complexity**\n`O(n logn)`.\n`O(n)` steps in the iteration, since we have to complete at most `n` buildings before finding out the maximum score. Binary search in each step takes `O(logn)` (I think it can be reduced to `O(1)` since the minimum flower is monotonically decreasing, as we increase the number of complete gardens).\n\n\n**Code**\n```\nclass Solution:\n def maximumBeauty(self, A: List[int], new: int, t: int, full: int, part: int) -> int:\n A = [min(t, a) for a in A]\n A.sort()\n\t\t\n\t\t# Two edge cases\n if min(A) == t: return full * len(A)\n if new >= t * len(A) - sum(A):\n return max(full*len(A), full*(len(A)-1) + part*(t-1))\n \n\t\t# Build the array `cost`.\n cost = [0]\n for i in range(1, len(A)):\n pre = cost[-1]\n cost.append(pre + i * (A[i] - A[i - 1]))\n\n\t\t# Since there might be some gardens having `target` flowers already, we will skip them.\n j = len(A) - 1\n while A[j] == t:\n j -= 1\n \n\t\t# Start the iteration\n ans = 0\n while new >= 0:\n\t\t\n\t\t\t# idx stands for the first `j` gardens, notice a edge case might happen.\n idx = min(j, bisect_right(cost, new) - 1)\n\t\t\t\n\t\t\t# bar is the current minimum flower in the incomplete garden\n bar = A[idx] + (new - cost[idx]) // (idx + 1)\n\t\t\t\n ans = max(ans, bar * part + full *(len(A) - j - 1))\n \n\t\t\t# Now we would like to complete garden j, thus deduct the cost for garden j \n\t\t\t# from new and move on to the previous(next) incomplete garden!\n\t\t\tnew -= (t - A[j])\n j -= 1\n \n return ans\n```
109,109
Maximum Total Beauty of the Gardens
maximum-total-beauty-of-the-gardens
Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a 0-indexed integer array flowers of size n, where flowers[i] is the number of flowers already planted in the ith garden. Flowers that are already planted cannot be removed. You are then given another integer newFlowers, which is the maximum number of flowers that Alice can additionally plant. You are also given the integers target, full, and partial. A garden is considered complete if it has at least target flowers. The total beauty of the gardens is then determined as the sum of the following: Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers.
Array,Two Pointers,Binary Search,Greedy,Sorting
Hard
Say we choose k gardens to be complete, is there an optimal way of choosing which gardens to plant more flowers to achieve this? For a given k, we should greedily fill-up the k gardens with the most flowers planted already. This gives us the most remaining flowers to fill up the other gardens. After sorting flowers, we can thus try every possible k and what is left is to find the highest minimum flowers we can obtain by planting the remaining flowers in the other gardens. To find the highest minimum in the other gardens, we can use binary search to find the most optimal way of planting.
1,102
7
First of all, we would need to find the minimum and maximum number of complete gardens that can be formed using ```newFlowers``` . This can be easily done using sorting.\n\nThe most important to thing to figure out in this problem is the minimum number of flowers present in a garden, if ```x``` gardens are already complete after using some (if not all) ```newFlowers```. We will then iterate from ```minComplete``` garden to ```maxComplete``` garden, and keep track of the maximum answer.\n\nNow to find minimum number of flowers present for ```x``` complete gardens, we need to store the prefix difference array. What is the motivation? See, we have to maximise the minimum value of flowers for every garden. So we start increasing from the smallest to the next largest. For that, we will need the difference times the number of elements we have to increase.\n\nFor example, suppose for the ```flowers = [2, 5, 6, 11, 13]``` if we want to have minimum value to be 5 we need at least ```5 - 2 = 3``` flowers. Now, if we need 6 minimum value, then we need ```(6 - 5) * 2 + 3 = 4``` flowers. This was the pattern. Also, make sure that this value that you increment doesn\'t make it equal to target.\n\nLastly, we will be having some ```newFlowers```, we find the least value for which it is possible, and then we may have some remaining flowers, we can then check for remaining group whether it is possible to increase that minimum value or not. \n\nLook at the code for better understanding.\n\n```\nclass Solution {\npublic:\n long long maximumBeauty(vector<int>& flowers, long long newFlowers, int target, int full, int partial) {\n int tot = flowers.size();\n long long maxBeauty = 0ll;\n int maxComplete = 0, minComplete = 0;\n sort(flowers.begin(), flowers.end());\n long long tempNewFlowers = newFlowers;\n for (int i = tot - 1; i >= 0; i--) {\n if (flowers[i] >= target) {\n minComplete++;\n maxComplete++;\n }\n else if (target - flowers[i] <= tempNewFlowers) {\n maxComplete++;\n tempNewFlowers -= target - flowers[i];\n } else {\n break;\n }\n }\n flowers.push_back(target - 1);\n vector<long long> preDif(tot + 1, 0ll);\n for (int i = 1; i < tot; i++) {\n preDif[i] = (long long)(i * (flowers[i] - flowers[i - 1])) + preDif[i - 1];\n }\n int right = tot - 1;\n while(right >= 0 && flowers[right] >= target) {\n right--;\n }\n if (right >= 0) {\n flowers[right + 1] = target - 1;\n preDif[right + 1] = preDif[right] + (long long) (right + 1) * (long long)(flowers[right + 1] - flowers[right]); \n }\n vector<long long> minFlower(maxComplete + 1);\n for (int complete = minComplete; complete <= maxComplete && right >= 0; complete++) {\n int pos = upper_bound(preDif.begin(), preDif.begin() + right + 1, newFlowers) - preDif.begin();\n pos--;\n minFlower[complete] = min((long long)target - 1, (long long)flowers[pos] + (long long)((newFlowers - preDif[pos]) / (pos + 1)));\n newFlowers -= (target - flowers[right]);\n right--;\n if (right >= 0) {\n flowers[right + 1] = target - 1;\n preDif[right + 1] = preDif[right] + (long long) (right + 1) * (long long)(flowers[right + 1] - flowers[right]); \n }\n }\n for (int complete = minComplete; complete <= maxComplete; complete++) {\n maxBeauty = max(maxBeauty, (long long)complete * (long long)full + minFlower[complete] * (long long)partial);\n }\n return maxBeauty;\n }\n};\n```
109,110
Maximum Total Beauty of the Gardens
maximum-total-beauty-of-the-gardens
Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a 0-indexed integer array flowers of size n, where flowers[i] is the number of flowers already planted in the ith garden. Flowers that are already planted cannot be removed. You are then given another integer newFlowers, which is the maximum number of flowers that Alice can additionally plant. You are also given the integers target, full, and partial. A garden is considered complete if it has at least target flowers. The total beauty of the gardens is then determined as the sum of the following: Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers.
Array,Two Pointers,Binary Search,Greedy,Sorting
Hard
Say we choose k gardens to be complete, is there an optimal way of choosing which gardens to plant more flowers to achieve this? For a given k, we should greedily fill-up the k gardens with the most flowers planted already. This gives us the most remaining flowers to fill up the other gardens. After sorting flowers, we can thus try every possible k and what is left is to find the highest minimum flowers we can obtain by planting the remaining flowers in the other gardens. To find the highest minimum in the other gardens, we can use binary search to find the most optimal way of planting.
2,474
17
First, sort the `flowers` list in ascending order. If we want to make some gardens full, we should choose those with more planted flowers to "fulfill".\n\nAssume that we want to get scores by making the largest `k` gardens full, while the rest `n-k` gardens have a max-min value of `flowers`. We need to sum up all missing values of the largest `k` flowers `sum[(max(0,target-flower) for flower in flowers[:-k]]`, which can be optimized by a "reversed" prefix sum array (for *prefix sum*, see [LC 303]()) in a O(n) time. Here, I use `lack[k]` to accumulate the total flowers required to make the largest `k` `flower` full. (**Note**: In some corner cases, all gardens are already full before planting new flowers, as we can\'t remove any planted flowers. Thus, we should start `k` with the min one that lets `lack[i]`>0 to avoid handling some full gardens as *incomplete* ones.)\n\nAfter fulfilling `k` gardens, the rest `n-k` gardens can be planted with **at most** `newFlowers-lack[k]` flowers. We\'re just curious about what is the max min value when adding `newFlowers-lack[k]` to `flowers[:n-k]`. This question satisfies the property of *binary-search* with a lower bound as `flowers[0]` (the origin min value) and an upper bound as `target` (**Note**: *In fact, after adding all `newFlowers-lack[k]`, the min value of `flowers[:n-k]` may >= `target`. However, we don\'t want to account for this case here because it will be considered later when we increase `k` to `n`, so the upper bound is limited to `target-1` inclusively*), so the score from the remaining `n-k` incomplete gardens can be obtained in `O(log(target)*cost(condition))`, in which `cost(condition)` denotes the time cost to check if the current min-value `flower` can be achieved by adding `newFlowers-lack[k]` flowers.\n \nTraditionally, finding the max-min value of an array after adding some numbers is a typical **load balancer problem**, which is similar to Q3 this week and the first challenge problem hosted by Amazon Last Mile Delivery last week. But the traditional linear way to calculate the max-min value is of time complexity in `O(n)` even with the auxiliary of the pre-sum array, which leads to a TLE in the contest. To reduce the runtime, we just need to check if a min `flower` can be achieved after adding `f` new flowers to the first `k` gardens *optimally*, here I use `fill(flower, f, k)` as a conditional checker to determine if it is feasible to all first `k` gardens are of >= `flower` flowers. Given the `fill` function, we can quickly apply the [binary search template]() to finish the skeleton of getting the actual max-min of `flower[:k]`.\n\nNow, let\'s look into `fill(flower, f, k)`: we check how many elements < `flower` there by binary-search as well, we call it `m`. Then, we try to make up the total diff values between those elements and our required `flower`, so we just need to check if the sum of the first `m` elements >= `m*flower` after adding `m` to the left-hand of the inequity, which can be easily solved when we have already known the sum of first `m` elements by pre-sum array, so `fill(flower, f, k)` is called in `O(log(n))`, which is the complexity of `cost(condition)` .\n\nFinally, we traverse the `flowers` linearly to consider `k` garden full and `n-k` gardens incomplete, the total score is `k*full + flower*partial`, in which `flower` is the max-min value of the `n-k` incomplete gardens, which is calculated by the binary search method above in `O(log(target)*log(n))`, along with a space complexity `O(n)`. (`n` = `len(flowers)`)\n\n\n```py\nimport bisect\nclass Solution:\n def maximumBeauty(self, flowers: List[int], newFlowers: int, target: int, full: int, partial: int) -> int:\n n = len(flowers)\n flowers.sort()\n pre,lack = [0],[0]\n \n # corner case in which no incomplete garden can be created. \n if flowers[0] >= target:\n return n*full\n \n # pre-sum in an ascending order\n for i in flowers:\n pre.append(pre[-1]+i)\n \n # pre-sum in a descending order, meanwhile, count how many gardens are already full\n cnt = 0\n for i in flowers[::-1]:\n if i >= target:\n cnt+=1\n lack.append(lack[-1]+max(target-i,0))\n \n # conditional checker: whether all first k elements can >= flower after adding f to them\n def fill(flower,f,k):\n i = bisect.bisect_left(flowers,flower,lo=0,hi=k)\n return pre[i] + f >= i*flower\n \n res = 0\n # start from the min number of full gardens\n for k in range(cnt,n):\n if lack[k] < newFlowers:\n left, right = flowers[0], target+1\n while left < right:\n mid = (left+right)//2\n if not fill(mid,newFlowers-lack[k],n-k):\n right = mid\n else:\n left = mid + 1\n left -= 1\n \n if left >= target:\n # the n-k gardens must be incomplete, which can have a max value as target-1\n \n res = max(res,(target-1)*partial+k*full)\n else:\n res = max(res,k*full+left*partial)\n \n # A corner case: All n gardens can be full, no incomplete gardens\n if lack[-1] <= newFlowers:\n res = max(res,n*full)\n return res\n \n \n```\nI know it looks ugly, but anyway, it is accepted.\n\n**Update**: credit to [@ithachien]() (see the comment below), I realize that in the last corner case (all gardens can be fulfilled) we don\'t have to do binary search to find out the max-min value of the first `n-k` gardens. It must be able to reach the largest min value as `target-1` because the remaining flowers are always sufficient, so I added the "short-circuitting" case before the loop as:\n\n```py\nres = 0\nif lack[-1] <= newFlowers:\n res = max(res,n*full)\n for k in range(cnt,n):\n res = max(res,(target-1)*partial+k*full)\n return res\n```\n\nBesides, the lower bound of the max-min value for the first `n-k` garden after planting the remaining flowers can be further increased to `(newFlowers-lack[k])//(n-k) + flowers[0]` as all flowers are evenly assigned to all `n-k` garden, which narrows down the search range.\n\nBased on the minor optimization above, my code turned out to be of a runtime in 2432 ms, and beats 100% Python3 submissions so far.
109,112
Maximum Total Beauty of the Gardens
maximum-total-beauty-of-the-gardens
Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a 0-indexed integer array flowers of size n, where flowers[i] is the number of flowers already planted in the ith garden. Flowers that are already planted cannot be removed. You are then given another integer newFlowers, which is the maximum number of flowers that Alice can additionally plant. You are also given the integers target, full, and partial. A garden is considered complete if it has at least target flowers. The total beauty of the gardens is then determined as the sum of the following: Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers.
Array,Two Pointers,Binary Search,Greedy,Sorting
Hard
Say we choose k gardens to be complete, is there an optimal way of choosing which gardens to plant more flowers to achieve this? For a given k, we should greedily fill-up the k gardens with the most flowers planted already. This gives us the most remaining flowers to fill up the other gardens. After sorting flowers, we can thus try every possible k and what is left is to find the highest minimum flowers we can obtain by planting the remaining flowers in the other gardens. To find the highest minimum in the other gardens, we can use binary search to find the most optimal way of planting.
3,585
49
I do not think that we need a binary search here.\n\nWe sort gardens (descending), and then go left to right and make gardens full (until we run out of flowers). Thus, our first pointer `p1` indicates full gardens, and the last garden defines the minimum number of flowers (`minF`) among all gardens.\n \n> There is a special case when we can make all gardens full - it may be better to only plant `target - 1` flowers in the last garden, if `(target - 1) * partial > full`.\n\nWe then go right-to-left, and try increasing the minimum number of flowers. The second pointer - `p2` - indicates how many gardens have less flowers than `minF`.\n \nWe plan necessary flowers to gardens right of `p2`. If we do not have enough flowers, we take it from the rightmost full garden, decreasing `p1`. For each `minF` we can achieve, we track and return the maximum beauty.\n\nHere is an example for `[9, 7, 7, 6, 5, 4, 3, 2, 1, 1]` gardens, with target `8` and `9` new flowers to plant. As you see, for `minF == 2`, we have 5 full gardens. For `minF == 3`, we move `p1` to get enough flowers to plant, and now we have 4 full gardens. \n\n![image]()\n\n**C++**\n```cpp\nlong long maximumBeauty(vector<int>& fl, long long newFlowers, int target, int full, int partial) {\n sort(begin(fl), end(fl), greater<int>());\n long long p1 = 0, sum = 0, res = 0, sz = fl.size();\n for (; p1 < sz; ++p1) {\n if (target - fl[p1] > newFlowers)\n break;\n newFlowers -= max(0, target - fl[p1]);\n }\n if (p1 == sz)\n return max(sz * full, (sz - 1) * full + (fl.back() < target ? (long long)(target - 1) * partial : full));\n for (long long minF = fl.back(), p2 = fl.size() - 1; minF < target; ) {\n while (p2 >= p1 && fl[p2] <= minF)\n sum += fl[p2--];\n int needed = (sz - p2 - 1) * minF - sum;\n if (needed > newFlowers) {\n if (--p1 < 0)\n break;\n newFlowers += max(0, target - fl[p1]);\n }\n else {\n res = max(p1 * full + minF * partial, res); \n ++minF;\n }\n }\n return res;\n}\n```
109,113
Maximum Total Beauty of the Gardens
maximum-total-beauty-of-the-gardens
Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a 0-indexed integer array flowers of size n, where flowers[i] is the number of flowers already planted in the ith garden. Flowers that are already planted cannot be removed. You are then given another integer newFlowers, which is the maximum number of flowers that Alice can additionally plant. You are also given the integers target, full, and partial. A garden is considered complete if it has at least target flowers. The total beauty of the gardens is then determined as the sum of the following: Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers.
Array,Two Pointers,Binary Search,Greedy,Sorting
Hard
Say we choose k gardens to be complete, is there an optimal way of choosing which gardens to plant more flowers to achieve this? For a given k, we should greedily fill-up the k gardens with the most flowers planted already. This gives us the most remaining flowers to fill up the other gardens. After sorting flowers, we can thus try every possible k and what is left is to find the highest minimum flowers we can obtain by planting the remaining flowers in the other gardens. To find the highest minimum in the other gardens, we can use binary search to find the most optimal way of planting.
2,364
13
Note that if we make `i` gardens full, then for the optimal solution, those gardens are the `i` biggest ones.\n```\nclass Solution {\npublic:\n long long maximumBeauty(vector<int>& flowers, long long newFlowers, int target, int full, int partial) {\n sort(flowers.begin(), flowers.end());\n int full_cnt = 0;\n for(int i = flowers.size() - 1; i >= 0; i--) {\n if(flowers[i] < target) break;\n full_cnt++;\n }\n int n = flowers.size() - full_cnt;\n if(n == 0) return (long long)full_cnt * (long long)full;\n \n vector<long long> fill_up(n, 0), fill_target(n, 0);\n \n // fill_up: flowers needed to get min of flowers to flowers[i]\n fill_up[0] = 0;\n for(int i = 1; i < n; i++) {\n fill_up[i] = (flowers[i] - flowers[i-1]) * (long long)i + fill_up[i-1];\n }\n // fill_target[i] fill flowers[i] to flowers[n-1] to target level\n fill_target[n-1] = (long long) target - flowers[n-1];\n for(int i = n - 2; i >= 0; i--) {\n fill_target[i] = fill_target[i+1] + (long long)(target - flowers[i]); \n }\n long long ret = 0;\n for(int num_fill = 0; num_fill <= n; num_fill++) {\n long long m = 0;\n long long rm = newFlowers;\n if(num_fill != 0) {\n rm -= fill_target[n-num_fill];\n }\n if(rm < 0) break;\n if(num_fill != n) {\n auto ptr = upper_bound(fill_up.begin(), fill_up.end(), rm);\n // can get min to flowers[idx-1] level, but not flowers[idx] level\n int idx = ptr - fill_up.begin();\n if(idx >= n - num_fill) idx = n - num_fill;\n m = flowers[idx - 1];\n m += (rm - fill_up[idx - 1]) / idx; \n m = min(m, (long long)target - 1);\n }\n long long tmp = m * (long long) partial + (full_cnt + num_fill) * (long long) full;\n ret = max(tmp, ret);\n }\n return ret;\n }\n};\n```
109,114
Maximum Total Beauty of the Gardens
maximum-total-beauty-of-the-gardens
Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a 0-indexed integer array flowers of size n, where flowers[i] is the number of flowers already planted in the ith garden. Flowers that are already planted cannot be removed. You are then given another integer newFlowers, which is the maximum number of flowers that Alice can additionally plant. You are also given the integers target, full, and partial. A garden is considered complete if it has at least target flowers. The total beauty of the gardens is then determined as the sum of the following: Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers.
Array,Two Pointers,Binary Search,Greedy,Sorting
Hard
Say we choose k gardens to be complete, is there an optimal way of choosing which gardens to plant more flowers to achieve this? For a given k, we should greedily fill-up the k gardens with the most flowers planted already. This gives us the most remaining flowers to fill up the other gardens. After sorting flowers, we can thus try every possible k and what is left is to find the highest minimum flowers we can obtain by planting the remaining flowers in the other gardens. To find the highest minimum in the other gardens, we can use binary search to find the most optimal way of planting.
1,190
17
/*\n \n Pre-Requisites :--> Prefix Sum + Binary Search\n \n Logic in a Nutshell :--> Actually in these type of questions , where the optimal answer is dependent on two distinct entities ,\n \n We used to fix one entity and try to change ( increment / decrement ) its value ; and then figure out what \n \n is the impact of the first operation on the second entity.\n \n \n Maybe , it sounds not so good , but analyzing the question you can easily get that Our answer depends on \n \n (1) Number of full flowers --> (num_full*fullValue) --> val1\n (2) Minimum value of Incomplete flower --> (min_incomp*partialValue) --> val2\n \n \n And the optimal answer will be the maxValue from any of the combinations of these two entity \n \n [ e.g :- 2 full flower + 3 partial flower\n 4 full flower + 1 partial flower\n 1 full flower + 3 partial flower ]\n \n \n Approach :--> But how can we determine which valid combination fetchs us our desired output.\n \n For these we have to make some basic but important observations ........\n \n \n Observation(1) --> We are given with fixed value of newFlowers (Let us consider it K) . Now we can use atmost K flowers.\n \n So how can we use minimum number of newFlowers and get maximum number of full flowers( whose value >= taregt) ???\n \n So obviously , we have to pick the Maximum valued flowers and try to put extra flowers till flowers[i]!=target.\n \n [ E.g :- flowers [2,4,6,7,9] , newFlowers = 5 , fullValue = 10 ---> Now we pick the flowers[4]=9 and use 1 flower .......]\n \n \n Observation(2) --> Now after we are done with the first part ( Current number of full flowers that we can achieve using atmost newFlowers amount of flowers ) \n \n After using certain amount of flowers in making certain amount of flowers "full" , let us say we have "rest" amount of newFlowers , we have to decide what we can do further with these amount of flowers.\n \n So , for these we have to look at the definition of\n \n "sumofbeauty" --> "# of full flowers * fullVal " + " Minimum valued incomplete flower * partialVal "\n \n \n So it is not that we can make one flower[i] so big with "rest" flowers , as the minimum incomplete flowers[i] remains the same and it will not increment our result that much.\n \n Well ,we have to evenly distribute the "rest" flowers to all of the incomplete flowers and pick the Minimum one.\n \n wait wait , so as a whole we have to maximize the minimum flowers[i] --> bang on !!! Here comes the approach of Binary Search.\n \n Finally , we have to fix the value of the incomplete flowers [ which have flowers[i] < target ] to "mid" and check whether all the incomplete flowers can reach to the "mid" value and if yes then increment the value properly. \n \n */\n\t\n\t`class Solution {\npublic:\n \n\n typedef long long ll;\n \n long long maximumBeauty(vector<int>& flowers, long long newFlowers, int target, int full, int partial) {\n \n ll n=flowers.size();\n \n sort(flowers.begin(),flowers.end());\n \n vector<ll>prefix(n,0LL);\n \n prefix[0]=flowers[0];\n \n for(ll i=1;i<n;i++){\n prefix[i]=prefix[i-1]+(ll)flowers[i];\n }\n \n \n ll max_beauty=0LL;\n \n // Travrese from the end of the array as discussed previously.......\n \n // Check Whether we can make full flowers from index n-1 to index i [ if not then break ]\n \n // There is one additional corner case --> Sometimes it will be optimal that we\'ll select 0 number of full flowers and try to maximize the partial_beauty using newFlowers.\n \n \n for(ll i=n;i>=0;i--){\n \n if(i==n){\n \n \n }\n \n else{\n \n ll req_for_full=max(0LL,(ll)(target-flowers[i]));\n \n if(req_for_full > newFlowers){\n break;\n }\n \n newFlowers-=req_for_full; \n \n flowers.pop_back(); // This the line where your code fails even after it is correct logically , as there is some situation when number of full flowers and number of partial flowers can collide and it increase our answer than the actual one . Try the Example TestCase 2 by your own.\n \n }\n \n \n ll curr_beauty_full=((n-i)*full);\n \n ll curr_beauty_partial=0LL;\n \n ll low=0,high=target-1;\n \n while(low<=high){\n \n ll mid=(low+high)/2;\n \n ll idx=upper_bound(flowers.begin(),flowers.end(),mid)-flowers.begin();\n \n if(idx==0){\n \n low=mid+1;\n \n }\n \n else{\n \n ll have_flowers=prefix[idx-1];\n \n ll req_flowers=(idx*mid);\n \n ll extra_flowers=(req_flowers-have_flowers);\n \n if(extra_flowers<=newFlowers){\n \n curr_beauty_partial=(mid*partial);\n \n low=mid+1;\n \n }\n \n else{\n \n high=mid-1;\n \n }\n \n }\n \n }\n \n max_beauty=max(max_beauty,curr_beauty_partial+curr_beauty_full);\n \n }\n \n return max_beauty;\n \n }\n};`
109,115
Maximum Total Beauty of the Gardens
maximum-total-beauty-of-the-gardens
Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a 0-indexed integer array flowers of size n, where flowers[i] is the number of flowers already planted in the ith garden. Flowers that are already planted cannot be removed. You are then given another integer newFlowers, which is the maximum number of flowers that Alice can additionally plant. You are also given the integers target, full, and partial. A garden is considered complete if it has at least target flowers. The total beauty of the gardens is then determined as the sum of the following: Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers.
Array,Two Pointers,Binary Search,Greedy,Sorting
Hard
Say we choose k gardens to be complete, is there an optimal way of choosing which gardens to plant more flowers to achieve this? For a given k, we should greedily fill-up the k gardens with the most flowers planted already. This gives us the most remaining flowers to fill up the other gardens. After sorting flowers, we can thus try every possible k and what is left is to find the highest minimum flowers we can obtain by planting the remaining flowers in the other gardens. To find the highest minimum in the other gardens, we can use binary search to find the most optimal way of planting.
1,830
7
```python\nclass Solution:\n def maximumBeauty(self, A: List[int], to_add: int, target: int, full: int, partial: int) -> int:\n N = len(A)\n A.sort()\n P = list(accumulate(A, initial=0))\n \n ans = 0\n j = N - 1\n for k in range(N + 1):\n j = min(j, N - k - 1)\n while j >= 0:\n h = (P[j + 1] + to_add) // (j + 1)\n if h < A[j] and j >= 0:\n j -= 1\n else:\n break\n\n cand = k * full\n if j >= 0 and A[j] < target:\n cand += min(h, target - 1) * partial\n ans = max(ans, cand)\n \n if k == N:\n break\n if (delta := target - A[~k]) > 0:\n to_add -= delta\n if to_add < 0:\n break\n \n return ans\n```\n\nSort `A`. You should take `k` plants and make them a height of `target`, and then try to improve the remaining `A[..j]` of them to be the best height possible.\n\nSince `j` is monotone decreasing as `k` increases, we can slide `j` down. In the while loop `j >= 0`, we search for the largest `j` such that we can make `A[..j]` atleast the height `h` of `A[j]`.\n\nNow we have a candidate answer: `k` completed plants, plus a height of `h` for the partial. There is a corner case where the height `h` as well as `A[j]` must be less than `target` for it to count.
109,116
Maximum Total Beauty of the Gardens
maximum-total-beauty-of-the-gardens
Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a 0-indexed integer array flowers of size n, where flowers[i] is the number of flowers already planted in the ith garden. Flowers that are already planted cannot be removed. You are then given another integer newFlowers, which is the maximum number of flowers that Alice can additionally plant. You are also given the integers target, full, and partial. A garden is considered complete if it has at least target flowers. The total beauty of the gardens is then determined as the sum of the following: Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers.
Array,Two Pointers,Binary Search,Greedy,Sorting
Hard
Say we choose k gardens to be complete, is there an optimal way of choosing which gardens to plant more flowers to achieve this? For a given k, we should greedily fill-up the k gardens with the most flowers planted already. This gives us the most remaining flowers to fill up the other gardens. After sorting flowers, we can thus try every possible k and what is left is to find the highest minimum flowers we can obtain by planting the remaining flowers in the other gardens. To find the highest minimum in the other gardens, we can use binary search to find the most optimal way of planting.
1,184
5
```\nclass Solution {\npublic:\n long long maximumBeauty(vector<int>& flowers, long long newFlowers, int target, int full, int partial) {\n long long ans = 0;\n int n = flowers.size();\n if(n == 0) return 0;\n sort(flowers.begin(), flowers.end());\n vector<long long> pref(n, 0); // Prefix sums array\n pref[0] = flowers[0];\n for(int i = 1; i < n; i++) {\n pref[i] = pref[i - 1] + flowers[i];\n }\n for(int i = n; i >= 0; i--) {\n // When i is n, none of the elements are incremented till target.\n if(i < n) { // The ith element(0-indexed) is incremented till target. This is handling the case of "full". We are doing this from the end because it will cost the least number of new Flowers.\n long long toAdd = max(0, target - flowers[i]);\n if(newFlowers < toAdd) {\n break; // We are breaking because we would\'ve already found the best answer in the previous iterations\n }\n newFlowers -= toAdd;\n flowers.pop_back();\n }\n long long beautyForFullCase = (long long)(n - i) * full; // All the elements from i to n -1 are incremented till target, so they have a beauty of (n - 1) * full\n \n // Here, we do binary search on x, which is the the maximum number we can increment all the numbers from 0 to i - 1 to. The maximum we can increment to is target-1 because after that, "partial" will not be applicable. Binary search is done to find out the maximum possible answer for the partial case.\n int l = 0, r = target - 1;\n long long beautyForPartialCase = 0;\n while(l <= r) {\n long long mid = l + (r - l) / 2; // mid is the maximum number we can increment to\n auto it = upper_bound(flowers.begin(), flowers.end(), mid); // will point to an element that is atleast 1 more than the incomplete garden with most number of flowers\n if(it == flowers.begin()) { // there are no incomplete gardens\n l = mid + 1;\n } else {\n long long len = distance(flowers.begin(), it); // number of incomplete gardens\n long long sum = pref[len - 1];\n long long needed = ((long long)mid * len) - sum; // number of flowers needed to make "mid" as the minimum element\n if(needed <= newFlowers) { // if it is possible to plant flowers such that the minimum number of flowers for any garden is "mid", then we go to check for higher values through Binary search\n l = mid + 1;\n beautyForPartialCase = (long long)mid * partial; // (minimum number of flowers in any incomplete garden) * (partial) = total beauty of incomplete gardens\n } else {\n r = mid - 1;\n }\n }\n }\n ans = max(ans, beautyForFullCase + beautyForPartialCase); // checking if this answer is better than the previous answers computed.\n }\n return ans;\n }\n};\n```
109,117
Maximum Total Beauty of the Gardens
maximum-total-beauty-of-the-gardens
Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a 0-indexed integer array flowers of size n, where flowers[i] is the number of flowers already planted in the ith garden. Flowers that are already planted cannot be removed. You are then given another integer newFlowers, which is the maximum number of flowers that Alice can additionally plant. You are also given the integers target, full, and partial. A garden is considered complete if it has at least target flowers. The total beauty of the gardens is then determined as the sum of the following: Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers.
Array,Two Pointers,Binary Search,Greedy,Sorting
Hard
Say we choose k gardens to be complete, is there an optimal way of choosing which gardens to plant more flowers to achieve this? For a given k, we should greedily fill-up the k gardens with the most flowers planted already. This gives us the most remaining flowers to fill up the other gardens. After sorting flowers, we can thus try every possible k and what is left is to find the highest minimum flowers we can obtain by planting the remaining flowers in the other gardens. To find the highest minimum in the other gardens, we can use binary search to find the most optimal way of planting.
793
5
The idea is that after sorting the flowers array from low to high, in the optimal result, the full/compete gardens must be on the right side, while partial gardens are on the left. Otherwise, we are wasting some newFlowers thus the result can\'t be optimal.\n\nSo we just need to check every index and do 2 things:\n1) try to make the right part of current index all full, if not possible, simply continue to next index\n2) after making the right part all full, we need to calculate what is the maximum value of min flowers in the left part we can make with remaing newFlowers.\n\nStep 1) above can be done with pre_sum array easily. Step 2) is more tricky.\nThe algorithm I used is to keep an auxiliary dp array during iteration, which will store below information:\n- at index j: dp[j] = (j+1) * flowers[j] - presum[j+1]\n- essentially, the extra flowers needed to make every garden left of index j equal to flowers[j]\n- this dp array is guaranteed to be increasing order\n\nSo in order to achieve Step 2), we will do a binary search on the dp array to get the rightmost j index possible with remaining newFlowers (rem_flowers), and every garden left of index j (including j) will be brought up to the same min_partial value which satisfies:\n- min_partial * (j+1) - presum[j+1] <= rem_flowers\n- min_partial <= target - 1\n\nThe rest is just update max_beauty with min_partial and total full/complete gardens\n\nOverall time complexity O(NlogN), space complexity O(N)\n\n```\nclass Solution:\n def maximumBeauty(self, flowers: List[int], newFlowers: int, target: int, full: int, partial: int) -> int:\n \n\t\t# move out already completed garden\n already_complete = 0\n temp = []\n for f in flowers:\n if f >= target:\n already_complete += 1\n else:\n temp.append(f)\n\n max_beauty = 0\n \n flowers = temp\n flowers.sort()\n \n presum = [0] + list(accumulate(flowers))\n N = len(flowers)\n \n dp_arr = []\n \n for i in range(N+1):\n # iterate all index: left part is all partial, right part (>= i) is all complete\n \n # update the dp arr for binary search below\n if i < N:\n dp_arr.append((i+1) * flowers[i] - presum[i+1])\n \n right_sum = presum[-1] - presum[i]\n right_count = N - i\n \n # if can\'t make the right part all complete, go to next index\n if right_sum + newFlowers < right_count * target:\n continue\n \n # remaining flowers after making right part all complete\n rem_flowers = newFlowers - (right_count * target - right_sum)\n \n # binary search to find the maximum possible min flowers in the left part (named \'min_partial\')\n if i == 0:\n min_partial = 0\n else:\n j = min(bisect.bisect_right(dp_arr, rem_flowers) - 1, i-1)\n min_partial = min((rem_flowers + presum[j+1]) // (j+1), target-1)\n \n complete = right_count + already_complete\n max_beauty = max(max_beauty, complete * full + min_partial * partial)\n\n \n return max_beauty\n```
109,118
Minimum Number of Operations to Convert Time
minimum-number-of-operations-to-convert-time
You are given two strings current and correct representing two 24-hour times. 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times. Return the minimum number of operations needed to convert current to correct.
String,Greedy
Easy
Convert the times to minutes. Use the operation with the biggest value possible at each step.
4,467
77
\nSee my latest update in repo [LeetCode]()\n\n## Solution 1. Greedy\n\n* Compute the time difference in seconds\n* Greedily using `60, 15, 5, 1` operations. For each operation `op`, we use `diff / op` number of operations to turn `diff` to `diff % op`.\n\n```cpp\n// OJ: \n// Author: github.com/lzl124631x\n// Time: O(1)\n// Space: O(1)\nclass Solution {\n int getTime(string &s) {\n return stoi(s.substr(0, 2)) * 60 + stoi(s.substr(3));\n }\npublic:\n int convertTime(string current, string correct) {\n int diff = getTime(correct) - getTime(current), ops[4] = {60,15,5,1}, ans = 0;\n for (int op : ops) {\n ans += diff / op;\n diff %= op;\n }\n return ans;\n }\n};\n```
109,160
Minimum Number of Operations to Convert Time
minimum-number-of-operations-to-convert-time
You are given two strings current and correct representing two 24-hour times. 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times. Return the minimum number of operations needed to convert current to correct.
String,Greedy
Easy
Convert the times to minutes. Use the operation with the biggest value possible at each step.
3,778
54
Since we can only add minutes, the greedy approach would work.\n\n**C++**\n```cpp \nint convertTime(string current, string correct) {\n auto toMin = [](string &s) { \n \xA0 \xA0 \xA0 \xA0return s[0] * 600 + s[1] * 60 + s[3] * 10 + s[4] ;\n };\n int d = toMin(correct) - toMin(current);\n return d / 60 + d % 60 / 15 + d % 15 / 5 + d % 5;\n}\n```
109,161
Minimum Number of Operations to Convert Time
minimum-number-of-operations-to-convert-time
You are given two strings current and correct representing two 24-hour times. 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times. Return the minimum number of operations needed to convert current to correct.
String,Greedy
Easy
Convert the times to minutes. Use the operation with the biggest value possible at each step.
2,388
35
1. Convert times into minutes and then the problem becomes simpler. \n2. To minimize the number of total operations we try to use the largest possible change from `[60,15,5,1]` till possible.\n```\nclass Solution:\n def convertTime(self, current: str, correct: str) -> int:\n current_time = 60 * int(current[0:2]) + int(current[3:5]) # Current time in minutes\n target_time = 60 * int(correct[0:2]) + int(correct[3:5]) # Target time in minutes\n diff = target_time - current_time # Difference b/w current and target times in minutes\n count = 0 # Required number of operations\n\t\t# Use GREEDY APPROACH to calculate number of operations\n for i in [60, 15, 5, 1]:\n count += diff // i # add number of operations needed with i to count\n diff %= i # Diff becomes modulo of diff with i\n return count\n```\n
109,164
Minimum Number of Operations to Convert Time
minimum-number-of-operations-to-convert-time
You are given two strings current and correct representing two 24-hour times. 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times. Return the minimum number of operations needed to convert current to correct.
String,Greedy
Easy
Convert the times to minutes. Use the operation with the biggest value possible at each step.
265
5
```\nclass Solution:\n def convertTime(self, current: str, correct: str) -> int:\n def toMinutes(s):\n h, m = s.split(\':\')\n return 60 * int(h) + int(m)\n \n minutes = toMinutes(correct) - toMinutes(current)\n hours, minutes = divmod(minutes, 60)\n quaters, minutes = divmod(minutes, 15)\n fives, minutes = divmod(minutes, 5)\n\n return hours + quaters + fives + minutes\n```
109,165
Minimum Number of Operations to Convert Time
minimum-number-of-operations-to-convert-time
You are given two strings current and correct representing two 24-hour times. 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times. Return the minimum number of operations needed to convert current to correct.
String,Greedy
Easy
Convert the times to minutes. Use the operation with the biggest value possible at each step.
908
13
"""\nclass Solution {\npublic:\n int convertTime(string current, string correct) {\n int hour1=(current[0]-\'0\')*10+(current[1]-\'0\');\n int hour2=(correct[0]-\'0\')*10+(correct[1]-\'0\');\n int minute1=(current[3]-\'0\')*10+(current[4]-\'0\');\n int minute2=(correct[3]-\'0\')*10+(correct[4]-\'0\');\n \n int total=(hour2-hour1)*60+ (minute2-minute1);\n int res=0;\n if(total>=60){\n int temp=(total/60);\n total-=(temp*60);\n res+=temp;\n }\n if(total>=15){\n int temp=(total/15);\n total-=(temp*15);\n res+=temp;\n }\n if(total>=5){\n int temp=(total/5);\n total-=(temp*5);\n res+=temp;\n }\n res+=total;\n return res;\n }\n};\n"""\n\tPlease Upvote if you Find it Helpful \uD83D\uDE42.
109,167
Minimum Number of Operations to Convert Time
minimum-number-of-operations-to-convert-time
You are given two strings current and correct representing two 24-hour times. 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times. Return the minimum number of operations needed to convert current to correct.
String,Greedy
Easy
Convert the times to minutes. Use the operation with the biggest value possible at each step.
1,730
23
**Here I am discussing my approach to this problem**\n**Approach:**\n1. Convert both **current time** and **correct time** into **minutes**.\n2. **Increase** **current time** by 60min until it becomes **just less or equal to correct time**.\n3. Similarly do the **same thing** with 15min, 5min, and 1min window.\n4. Count the **number of iterations** performed.\n5. Return the number of iterations.\n\n**Source Code:**\n```\nclass Solution {\n public int convertTime(String current, String correct) {\n String[] curr = current.split(":");\n String[] corr = correct.split(":");\n int cur = Integer.parseInt(curr[0]) * 60 + Integer.parseInt(curr[1]);\n int cor = Integer.parseInt(corr[0]) * 60 + Integer.parseInt(corr[1]);\n int count = 0;\n \n while(cur + 60 <= cor) {\n ++count;\n cur += 60;\n }\n \n while(cur + 15 <= cor) {\n ++count;\n cur += 15;\n }\n \n while(cur + 5 <= cor) {\n ++count;\n cur += 5;\n }\n \n while(cur + 1 <= cor) {\n ++count;\n cur += 1;\n }\n \n return count;\n \n }\n}\n```\n\n**Complexity Analysis:**\n```\nTime Complexity: O(c) // c some constant value <= 100\nSpace Complexity : O(1)\n```
109,168
Minimum Number of Operations to Convert Time
minimum-number-of-operations-to-convert-time
You are given two strings current and correct representing two 24-hour times. 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times. Return the minimum number of operations needed to convert current to correct.
String,Greedy
Easy
Convert the times to minutes. Use the operation with the biggest value possible at each step.
2,057
19
```java\n public int convertTime(String current, String correct){\n Function<String, Integer> parse = t -> Integer.parseInt(t.substring(0, 2)) * 60 + Integer.parseInt(t.substring(3));\n int diff = parse.apply(correct) - parse.apply(current), ops[] = {60, 15, 5, 1}, r = 0;\n for(int i = 0; i < ops.length && diff > 0; diff = diff % ops[i++])\n r += diff / ops[i];\n return r;\n }
109,169
Minimum Number of Operations to Convert Time
minimum-number-of-operations-to-convert-time
You are given two strings current and correct representing two 24-hour times. 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times. Return the minimum number of operations needed to convert current to correct.
String,Greedy
Easy
Convert the times to minutes. Use the operation with the biggest value possible at each step.
724
6
```\n1. extract the hours and minutes from both the strings\n2. convert the strings to numbers\n3. convert both time time to minutes.\n4. calculate the minutes difference.\n5. simply check minimum operations to make minutes equal to difference.\nclass Solution {\npublic:\n int convertTime(string a, string b) {\n int x=a[0]-\'0\',y=a[1]-\'0\',z=a[3]-\'0\',w=a[4]-\'0\';\n int p=b[0]-\'0\',q=b[1]-\'0\',r=b[3]-\'0\',s=b[4]-\'0\';\n int hr1 = (x)*10+(y);\n int m1 = (z)*10+(w);\n int hr2 = (p)*10+(q);\n int m2 = (r)*10+s;\n int num1 = hr1*60+m1;\n int num2 = hr2*60+m2;\n int diff = num2-num1;\n int res=0;\n int arr[4]={60,15,5,1};\n for(int i=0;i<4;i++){\n res+=diff/arr[i];\n diff = diff%arr[i];\n }\n return res;\n }\n};
109,171
Minimum Number of Operations to Convert Time
minimum-number-of-operations-to-convert-time
You are given two strings current and correct representing two 24-hour times. 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times. Return the minimum number of operations needed to convert current to correct.
String,Greedy
Easy
Convert the times to minutes. Use the operation with the biggest value possible at each step.
368
5
```\nclass Solution {\npublic:\n int convertTime(string current, string correct) {\n int curr_hour = stoi(current.substr(0,2));\n int curr_min = stoi(current.substr(3,2));\n int co_hour = stoi(correct.substr(0,2));\n int co_min = stoi(correct.substr(3,2));\n \n \n int h_diff = co_hour - curr_hour;\n int min_diff = co_min - curr_min;\n \n int total = h_diff*60 + min_diff; //Calculate The Total Minutes\n vector<int>time{1,5,15,60};\n \n int op = 0; // Perform the Greedy Operation\n for(int i = time.size() -1;i>=0;i--){\n if(total >= time[i] && total >0){\n op+=total/time[i]; \n total = total%time[i];\n }\n }\n \n \n \n return op;\n }\n};
109,173
Minimum Number of Operations to Convert Time
minimum-number-of-operations-to-convert-time
You are given two strings current and correct representing two 24-hour times. 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times. Return the minimum number of operations needed to convert current to correct.
String,Greedy
Easy
Convert the times to minutes. Use the operation with the biggest value possible at each step.
899
8
```\nclass Solution {\npublic:\n int convertTime(string current, string co) {\n \n string h1="";\n string m1="";\n string h2="";\n string m2="";\n \n h1+=current[0];\n h1+=current[1];\n \n m1+=current[3];\n m1+=current[4];\n \n h2+=co[0];\n h2+=co[1];\n \n m2+=co[3];\n m2+=co[4];\n \n \n int min1=stoi(h1)*60+stoi(m1);\n int min2=stoi(h2)*60+stoi(m2);\n \n // int x=min2-min1;\n int count=0;\n \n while(min2>min1){\n \n if((min2-min1)>=60){\n min1=min1+60;\n count++;\n }\n else if((min2-min1)>=15){\n min1=min1+15;\n count++;\n }\n else if((min2-min1)>=5){\n min1=min1+5;\n count++;\n }\n else {\n count+=(min2-min1);\n min1=min1+(min2-min1);\n }\n }\n return count;\n \n }\n};\n```
109,174
Minimum Number of Operations to Convert Time
minimum-number-of-operations-to-convert-time
You are given two strings current and correct representing two 24-hour times. 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times. Return the minimum number of operations needed to convert current to correct.
String,Greedy
Easy
Convert the times to minutes. Use the operation with the biggest value possible at each step.
392
5
Found this solution helpful? Consider showing support by upvoting this post.\nHave a question? Kindly leave a comment below.\nThank you and happy hacking!\n```\nconst convertTime = (current, correct) => {\n if (current === correct) return 0\n\t\n let count = 0\n let currentInMins = parseInt(current.slice(3)) + parseInt(current.slice(0, 2)) * 60\n let correcttInMins = parseInt(correct.slice(3)) + parseInt(correct.slice(0, 2)) * 60\n let minuteDifference = correcttInMins - currentInMins\n\n while (minuteDifference !== 0) {\n if (minuteDifference % 60 === 0) {\n minuteDifference -= 60\n count++\n }\n else if (minuteDifference % 15 === 0) {\n minuteDifference -= 15\n count++\n }\n else if (minuteDifference % 5 === 0) {\n minuteDifference -= 5\n count++\n }\n else{\n minuteDifference -= 1\n count++\n }\n }\n\n return count\n};\n```
109,178
Add Two Integers
add-two-integers
null
Math
Easy
null
80,081
893
**Many of them are good template code, feel free to copy them for later use**\n\nWay 1: Binary Search\n```\nclass Solution {\n public int sum(int num1, int num2) {\n int l = -200, r = 200;\n while (l < r) {\n int mid = (l + r) >> 1;\n if (mid == num1 + num2) { return mid; }\n if (mid < num1 + num2) l = mid + 1;\n if (mid > num1 + num2) r = mid - 1;\n }\n return l;\n }\n}\n \n```\nWay 2: Brute Force\n```\nclass Solution {\n public int sum(int num1, int num2) {\n for (int i = -200; i <= 200; i++) {\n if (num1 + num2 == i) {\n return i;\n }\n }\n\t return -1;\n }\n}\n```\nWay 3: Shortest path - Dijkstra\n![image]()\nConsider distance between node 0 and 1 as num1 and distance between node 1 and 2 as num2, and the shortest path between node 0 and 2 yields the result of num1+num2. \n```\nclass Solution {\n List<int[]>[] adj = new List[3];\n int[] dis = new int[3];\n public int sum(int num1, int num2) {\n for (int i = 0; i < 3; i++) {\n adj[i] = new ArrayList<>();\n }\n adj[0].add(new int[] {1, num1});\n adj[1].add(new int[] {2, num2});\n return dijkstra(2, 0);\n }\n public int dijkstra(int dest, int source) {\n Arrays.fill(dis, Integer.MAX_VALUE);\n PriorityQueue<int[]> q = new PriorityQueue<>((a, b) -> {\n return a[0]-b[0];\n });\n q.add(new int[] {source, 0});\n while (!q.isEmpty()) {\n int[] cur = q.poll();\n dis[cur[0]] = cur[1];\n for (int[] nxt : adj[cur[0]]) {\n if (cur[1]+nxt[1]<dis[nxt[0]]) {\n q.add(new int[] {nxt[0], cur[1]+nxt[1]});\n }\n }\n }\n return dis[dest];\n }\n}\n```\nWay 4: Shortest path - Floyd\nIdea is same as above\n```\nclass Solution {\n int[][] dis = new int[3][3];\n public int sum(int num1, int num2) {\n for (int i = 0; i <= 2; i++) {\n Arrays.fill(dis[i], 10000);\n }\n dis[0][1] = num1;\n dis[1][2] = num2;\n return floyd(2, 0);\n }\n public int floyd(int dest, int source) {\n for (int k = 0; k <= 2; k++) {\n for (int i = 0; i <= 2; i++) {\n for (int j = 0; j <= 2; j++) {\n dis[i][j] = Math.min(dis[i][j], dis[i][k] + dis[k][j]);\n }\n }\n }\n return dis[source][dest];\n }\n}\n```\nWay 5: Prefix Sum\n```\nclass Solution {\n public int sum(int num1, int num2) {\n int[] A = new int[] {num1, num2};\n int[] prefixSum = new int[A.length+1];\n for (int i = 0; i < A.length; i++) {\n prefixSum[i+1] = prefixSum[i] + A[i];\n }\n return prefixSum[A.length];\n }\n}\n```\nWay 6: Suffix Sum\n```\nclass Solution {\n public int sum(int num1, int num2) {\n int[] A = new int[] {num1, num2};\n int[] suffixSum = new int[A.length+2];\n for (int i = A.length; i >= 1; i--) {\n suffixSum[i] = suffixSum[i+1] + A[i-1];\n }\n return suffixSum[1];\n }\n}\n```\nWay 7: Segment Tree Range Sum Query\n```\nclass Solution {\n int n = 2;\n int[] segTree = new int[n*4];\n int[] A;\n public int sum(int num1, int num2) {\n A = new int[] {num1, num2};\n build(1, n, 1);\n return querySum(1, n, 1, n, 1);\n }\n public int querySum(int l, int r, int ql, int qr, int idx) {\n if (l == ql && r == qr) return segTree[idx];\n int m = (l+r)/2;\n if (ql > m) return querySum(m+1, r,ql,qr,2*idx+1 );\n else if (qr<=m) return querySum(l, m, ql, qr,2*idx);\n else return querySum(l,m,ql, m, 2*idx) + querySum(m+1, r, m+1,qr, 2*idx+1);\n }\n public void build(int l, int r, int idx) {\n if (l == r) {\n segTree[idx] = A[l-1];\n return;\n }\n int m = (l+r)/2;\n build(l , m, idx*2); build(m+1, r, idx*2+1);\n segTree[idx] = segTree[2*idx] + segTree[2*idx+1];\n }\n}\n```\nWay 8: Binary Indexed Tree (Fenwick Tree) Range Sum Query\n```\nclass Solution {\n int n = 2;\n int[] bit = new int[n+1]; \n\n public int sum(int num1, int num2) {\n add(1, num1); add(2, num2);\n return querySum(1, n);\n }\n\n public int bitSum(int r) {\n int ret = 0;\n for (; r > 0; r-=(r&-r))\n ret += bit[r];\n return ret;\n }\n\n public int querySum(int l, int r) {\n return bitSum(r) - bitSum(l - 1);\n }\n\n public void add(int idx, int delta) {\n for (; idx < bit.length; idx+=(idx&-idx)) {\n bit[idx] += delta;\n }\n }\n}\n```\nWay 9: Bit Manipulation\n```\nclass Solution {\n public int sum(int num1, int num2) {\n if (num2 == 0) return num1;\n return sum(num1 ^ num2, (num1 & num2) << 1);\n }\n}\n```\n\nWay 10: Brute Force v2 (Suggested by zayne-siew)\n```\nclass Solution {\n public int sum(int num1, int num2) {\n int res = 0;\n while (num1 != 0) {\n res += inc(num1);\n num1 -= inc(num1);\n }\n while (num2 != 0) {\n res += inc(num2);\n num2 -= inc(num2);\n }\n return res;\n }\n \n private int inc(int num) {\n return num > 0 ? 1 : -1;\n }\n}\n```\nWay 11: Minimum Spanning Tree - Kruskal\n```\nclass Solution {\n int n = 3;\n List<edge> edges = new ArrayList<>();\n int [] rank = new int[n], leader = new int[n];\n public int sum(int num1, int num2) {\n for (int i = 0; i < n; i++) {\n leader[i] = i;\n }\n edges.add(new edge(0, 1, num1));\n edges.add(new edge(1, 2, num2));\n Collections.sort(edges);\n int ans = 0;\n for (edge nxt : edges) {\n if (find(nxt.u) != find(nxt.v)) {\n union(nxt.v, nxt.u);\n ans += nxt.w;\n }\n }\n return ans;\n }\n public void union(int a, int b){\n a = find(a); b = find(b);\n if(a != b) {\n if (rank[a] > rank[b]) {\n rank[a]++;\n leader[b] = a;\n } else {\n rank[b]++;\n leader[a] = b;\n }\n }\n }\n\n public int find(int n){\n if (n != leader[n]){\n leader[n] = find(leader[n]);\n }\n return leader[n];\n }\n public class edge implements Comparable<edge> {\n int u, v, w;\n edge(int i, int j, int c) {\n u = i; v = j; w = c;\n }\n\n @Override\n public int compareTo(edge o) {\n return w-o.w;\n }\n }\n}\n```\nWay 12: Directly Add (Lmaoooooo)\n```\nclass Solution {\n public int sum(int num1, int num2) {\n return num1+num2;\n }\n}\n```\nWay 13: Divide And Conquer \n```\nclass Solution {\n int n = 3;\n int[] A = new int[n];\n public int sum(int num1, int num2) {\n A[1] = num1; A[2] = num2;\n return fun(1, 2);\n }\n public int fun(int l, int r) { \n if (l==r) return A[l];\n int m = (l+r)>>1;\n return fun(l, m) + fun(m+1, r);\n }\n}\n```\nWay 14: Bellman\u2013Ford Algorithm\n```\nclass Solution {\n int n = 3, m = 2;\n List<e> edge = new ArrayList<>();\n public int sum(int num1, int num2) {\n edge.add(new e(0, 1, num1));\n edge.add(new e(1, 2, num2));\n return BellmanFord(0, 2);\n }\n public int BellmanFord(int src, int dest) {\n int[] dis = new int[n];\n Arrays.fill(dis, Integer.MAX_VALUE);\n dis[src] = 0;\n for (int i = 1; i < n; ++i) {\n for (int j = 0; j < m; ++j) {\n int u = edge.get(j).a;\n int v = edge.get(j).b;\n int w = edge.get(j).c;\n if (dis[u] != Integer.MAX_VALUE && dis[u] + w < dis[v])\n dis[v] = dis[u] + w;\n }\n }\n return dis[dest];\n }\n public class e {\n int a, b, c;\n e(int f, int s, int w) {\n a = f; b = s; c = w;\n }\n }\n}\n```\nWay 15: Quick Power(Exponentiation by squaring)\n```\nclass Solution {\n int M = (int) 1e9+7;\n public int sum(int num1, int num2) {\n return pow(num1, 1) + pow(num2, 1);\n }\n public int pow (int x, int exp){\n if (exp==0) return 1;\n int t = pow(x, exp/2);\n t = t*t % M;\n if (exp%2 == 0) return t;\n return t*x % M;\n }\n}\n```\nWay 16: Difference Array Range Add Operation\n```\nclass Solution {\n public int sum(int num1, int num2) {\n int[] dif = new int[4];\n List<range> add = new ArrayList<>(Arrays.asList(new range(1, 2, num1), new range(1, 2, num2)));\n for (range op : add) {\n dif[op.l] += op.v;\n dif[op.r+1] -= op.v;\n }\n for (int i = 1; i < 4; i++) {\n dif[i] += dif[i-1];\n }\n return dif[2];\n }\n public class range {\n int l, r, v;\n range(int lft, int rht, int val) {\n l = lft; r = rht; v = val;\n }\n }\n}\n```\nWay 17: Sparse Table RMQ\nConsider the int array A: {-1, 2, 10}, where num1 is 2 and num2 is 10. The value -1 is not part of the operation. Here range_min(left_bound_index = 1, right_bound_index = 2) = 2, and range_max(left_bound_index = 1, right_bound_index = 2) = 10, lastly the sum is 2+10 gives us the result of num1+num2 which is 12. \n```\nclass Solution {\n int n = 2;\n public int sum(int num1, int num2) {\n int[] A = new int[] {-1, num1, num2};\n int [][] maxTable = new int[n+1][(int) (Math.log(n)/Math.log(2))+1];\n int [][] minTable = new int[n+1][(int) (Math.log(n)/Math.log(2))+1];\n for (int i = 1; i <= n; i++) {\n maxTable[i][0] = A[i];\n minTable[i][0] = A[i];\n }\n for (int i = 1; 1<<i <= n; i++) {\n for (int j = 1; j+(1<<i)-1 <= n; j++) {\n maxTable[j][i] = Math.max(maxTable[j][i-1], maxTable[j+(1<<(i-1))][i-1]);\n minTable[j][i] = Math.min(minTable[j][i-1], minTable[j+(1<<(i-1))][i-1]);\n }\n }\n return minQuery(1, n, minTable) + maxQuery(1, n, maxTable); // interval max + interval min = nums1 + nums2\n }\n public int maxQuery(int l, int r, int [][] table) {\n int j = (int) (Math.log(r-l+1)/Math.log(2));\n return Math.max(table[l][j], table[r-(1<<j)+1][j]);\n }\n public int minQuery(int l, int r, int [][] table) {\n int j = (int) (Math.log(r-l+1)/Math.log(2));\n return Math.min(table[l][j], table[r-(1<<j)+1][j]);\n }\n}\n```\nWay 18: The Method Of Classification Discussion (suggested by greg66611)\n```\nclass Solution {\n public synchronized strictfp Integer sum(final int... a) { \n if (a[0]>a[1]){\n return -(a[1]-a[0]-a[1]-a[1]);\n }\n if (a[0]<a[1]){\n return -(a[0]-a[1]-a[0]-a[0]);\n }\n if (a[0]<0) {\n return -2*(a[0]-a[0]-a[0]);\n }\n return sum(a[0]-1,a[1]+1);\n }\n}\n```\nWay 19: Evaluation Of String Expression\nThis solution incorporates divide and conquer ideas of broken expression down into smaller parts to evaluate. Also note that this util function can also solve LeetCode [224. Basic Calculator]()\n```\nclass Solution {\n public int sum(int num1, int num2) {\n int sign1 = num1 < 0 ? -1 : 1;\n int sign2 = num2 < 0 ? -1 : 1;\n if (sign1 * sign2 == -1) {\n if (num1>num2) {\n String expression = num1 + "-" + num2;\n return eval((expression).toCharArray(), 0,expression.length()-1);\n }\n else {\n String expression = num2 + "-" + Math.abs(num1);\n return eval((expression).toCharArray(), 0,expression.length()-1);\n }\n } \n else {\n if (sign1<0) {\n String expression = "-(" + Math.abs(num1) + "+" + Math.abs(num2) + ")";\n return eval((expression).toCharArray(), 0,expression.length()-1);\n }\n else {\n String expression = num1 + "+" + num2;\n return eval((expression).toCharArray(), 0,expression.length()-1);\n }\n }\n }\n public int eval(char[] s, int l, int r) {\n Stack<Integer> nums = new Stack();\n int cur = 0;\n char sign = \'+\';\n for (int i = l; i <= r; i++) {\n if (Character.isDigit(s[i])) {\n cur = cur * 10 + s[i] - \'0\';\n }\n if (!Character.isDigit(s[i]) || i==r) {\n if (s[i] == \'(\') {\n int left = 1, right = 0;\n for (int j = i+1; j <= r; j++) {\n if (s[j]==\'(\') left++;\n else if (s[j]==\')\') right++;\n if (left==right) {\n cur = eval(s, i+1, j-1);\n i = j;\n break;\n }\n }\n }\n switch (sign) {\n case \'+\':\n nums.push(cur);\n break;\n case \'-\':\n nums.push(-cur);\n break;\n case \'*\':\n nums.push(cur * nums.pop());\n break;\n case \'/\':\n nums.push(nums.pop() / cur);\n break;\n }\n sign = s[i];\n cur = 0;\n }\n }\n int res = 0;\n while (!nums.isEmpty()) res+=nums.pop();\n return res;\n }\n}\n```\nWay 20: Merge Sort\n```\nclass Solution {\n int ans = 0;\n public int sum(int num1, int num2) {\n int[] A = new int[] {num1, num2};\n mergeSort(A, 0, 1);\n return ans;\n }\n public void mergeSort(int[] nums, int l, int r) {\n if (l>=r) return;\n int mid = l+r>>1;\n mergeSort(nums, l, mid); mergeSort(nums, mid+1, r);\n int i = l, j = mid+1, k = 0;\n int[] cur_sorted = new int[r-l+1];\n while (i<=mid && j<=r) {\n if (nums[i] <= nums[j]) {\n cur_sorted[k++] = nums[i++];\n }\n else cur_sorted[k++] = nums[j++];\n }\n while (i<=mid) cur_sorted[k++] = nums[i++];\n while (j<=r) cur_sorted[k++] = nums[j++];\n for (int m = 0; m < r-l+1; m++) {\n nums[m+l] = cur_sorted[m];\n ans+=cur_sorted[m]; // works since there\'s only two numbers\n }\n }\n}\n```\nWay 21: Bucket Sort\n```\nclass Solution {\n public int sum(int num1, int num2) {\n int[] A = new int[] {num1, num2};\n return bucketSort(A);\n }\n public int bucketSort(int[] nums) {\n int min = 1<<30, max = -(1<<30), n = nums.length;\n for (int v : nums) {\n min = Math.min(v, min);\n max = Math.max(v, max);\n }\n int range = max-min;\n int size = range/n+1;\n int bucketNum = n;\n List<Integer>[] buckets = new List[bucketNum];\n for (int i = 0; i < bucketNum; i++) {\n buckets[i] = new ArrayList<>();\n }\n for (int v : nums) {\n int idx = (v-min)/size;\n buckets[idx].add(v);\n }\n int ans = 0;\n for (List<Integer> sorted : buckets) {\n Collections.sort(sorted);\n for (int v : sorted) {\n ans+=v;\n }\n }\n return ans;\n }\n}\n```\n\n\n
109,209
Add Two Integers
add-two-integers
null
Math
Easy
null
11,596
144
```\n#define Actions class Solution {\n#define speak public: int sum(\n#define louder int num1, int num2) {\n#define than return num1 + num2; }\n#define words };\nActions speak louder than words\n```
109,213
Add Two Integers
add-two-integers
null
Math
Easy
null
7,023
45
\u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E \u200E
109,224
Add Two Integers
add-two-integers
null
Math
Easy
null
10,111
60
Welp, I deleted 1 line and added 1 line. So technically it\'s an 0-Line solution? :p\n```\nclass Solution:\n sum = add\n```
109,226
Add Two Integers
add-two-integers
null
Math
Easy
null
3,888
50
Convert to num1 to a LinkedList.\nConvert to num2 to a LinkedList.\nAdd the two LinkedLists.\nConvert the result LinkedList back to an integer.\n\n```\nclass Solution {\n \n final boolean TRUE = Boolean.TRUE;\n \n public int sum(int num1, int num2) {\n Node l1 = convertToList(num1);\n Node l2 = convertToList(num2);\n \n Node sumHead;\n if(num1 < 0 && num2 < 0)\n sumHead = addTwoNumbers(l1, l2, false);\n else if(num1 < 0) \n sumHead = addTwoNumbers(l2, l1, true);\n else if(num2 < 0) \n sumHead = addTwoNumbers(l1, l2, true);\n else\n sumHead = addTwoNumbers(l1, l2, false);\n \n int guess = 0;\n while(Boolean.valueOf(new String(new char[]{\'t\',(char) 114,\'u\',\'e\'})) == TRUE) {\n int digit = sumHead.val;\n \n guess *= 10;\n guess += digit;\n \n sumHead = sumHead.next;\n if(sumHead == null)\n break;\n }\n \n if(num1 < 0 && num2 < 0)\n guess = -guess;\n \n return guess;\n }\n \n private void print(Node head) {\n System.out.println();\n \n while(head != null) {\n System.out.print(head.val + " > ");\n head = head.next;\n }\n }\n \n private Node convertToList(int num) {\n if(num == 0)\n return new Node(0);\n \n Node head = null;\n \n boolean isNegative = num < 0;\n \n num = Math.abs(num);\n \n while(num > 0) {\n int digit = num % 10;\n\n Node digitNode = new Node(digit);\n digitNode.next = head;\n \n head = digitNode;\n \n num /= 10;\n }\n \n head.isNegative = isNegative;\n \n return head;\n }\n \n private Node addTwoNumbers(Node l1, Node l2, boolean negativeMode) {\n //reversing list\n Node head1 = reverse(l1);\n Node head2 = reverse(l2);\n \n Node answerHead = null;\n \n //process digits\n int carry = 0; //0 or 1\n while(head1 != null || head2 != null || carry == 1) {\n int a = head1 == null ? 0 : head1.val;\n int b = head2 == null ? 0 : head2.val;\n \n int total = a + b + carry;\n if(negativeMode)\n total = a - b;\n \n carry = 0; \n if(total >= 10) {\n carry = 1;\n total -= 10;\n }\n \n Node current = new Node(total);\n current.next = answerHead;\n answerHead = current;\n \n head1 = head1 == null ? null : head1.next;\n head2 = head2 == null ? null : head2.next;\n }\n \n return answerHead;\n }\n \n //returns head of reversed\n //could use stack to easily reverse. but it takes memory\n private Node reverse(Node oldHead) {\n if(oldHead == null)\n return null;\n \n Node prev = null;\n Node current = oldHead;\n Node next = current.next;\n //prev > current > next\n //are always consistent at the beginning\n //reverse the current.next\n while(current != null) {\n current.next = prev;\n \n prev = current;\n current = next;\n \n if(current != null)\n next = current.next;\n }\n \n oldHead.next = null;\n return prev;\n }\n \n public class Node {\n int val;\n Node next;\n boolean isNegative;\n \n Node() {}\n \n Node(int val) {\n this.val = val;\n }\n \n Node(int val, Node next) {\n this.val = val; this.next = next;\n }\n }\n}\n```
109,227
Add Two Integers
add-two-integers
null
Math
Easy
null
1,752
14
**If you find this solution easy and well explantory then do upvote (press up symbol present on left side) **\n\n\n int sum(int num1, int num2) {\n return num1+num2;\n }
109,231
Add Two Integers
add-two-integers
null
Math
Easy
null
1,286
8
# **Answer in Caption.**\n![up.png]()\n\n\n
109,232
Add Two Integers
add-two-integers
null
Math
Easy
null
4,481
8
# Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def sum(self, num1: int, num2: int) -> int:\n return num1 + num2\n```
109,236
Add Two Integers
add-two-integers
null
Math
Easy
null
1,192
7
Here you go. It doesn\'t use any add operations. I think this is the what the interviewer has in mind.\n\n```\nclass Solution {\npublic:\n int sum(int num1, int num2) {\n while(num2 != 0){\n int carry = num1 & num2;\n num1 = num1^num2;\n num2 = (carry & 0xffffffff)<< 1;\n }\n return num1;\n }\n};\n```
109,237
Add Two Integers
add-two-integers
null
Math
Easy
null
4,508
12
**There\u2019s nothing to write on it write a recipe for pancakes**\n\n# Code\n```\nclass Solution:\n def sum(self, num1: int, num2: int) -> int:\n return num1 + num2\n \n```\n\n**Pancake Ingredients**\nYou likely already have everything you need to make this pancake recipe. If not, here\'s what to add to your grocery list:\n\n\xB7 Flour: This homemade pancake recipe starts with all-purpose flour.\n\xB7 Baking powder: Baking powder, a leavener, is the secret to fluffy pancakes.\n\xB7 Sugar: Just a tablespoon of white sugar is all you\'ll need for subtly sweet pancakes.\n\xB7 Salt: A pinch of salt will enhance the overall flavor without making your pancakes taste salty.\n\xB7 Milk and butter: Milk and butter add moisture and richness to the pancakes.\n\xB7 Egg: A whole egg lends even more moisture. Plus, it helps bind the pancake batter together.\n\n**How to Make Pancakes From Scratch**\nIt\'s not hard to make homemade pancakes \u2014 you just need a good recipe. That\'s where we come in! You\'ll find the step-by-step recipe below, but here\'s a brief overview of what you can expect:\n\n1. Sift the dry ingredients together.\n2. Make a well, then add the wet ingredients. Stir to combine.\n3. Scoop the batter onto a hot griddle or pan.\n4. Cook for two to three minutes, then flip.\n5. Continue cooking until brown on both sides.\n\n**When to Flip Pancakes**\nYour pancake will tell you when it\'s ready to flip. Wait until bubbles start to form on the top and the edges look dry and set. This will usually take about two to\nthree minutes on each side.\n\n# Code\n```\nclass Solution:\n def sum(self, num1: int, num2: int) -> int:\n return num1 + num2\n \n```
109,240
Add Two Integers
add-two-integers
null
Math
Easy
null
3,579
23
**1. C++**\n```\nclass Solution {\npublic:\n int sum(int num1, int num2) {\n return num1 + num2;\n }\n};\n```\n**2. Java**\n```\nclass Solution {\n public int sum(int num1, int num2) {\n return num1 + num2;\n }\n}\n```\n**3. Python3**\n```\nclass Solution:\n def sum(self, num1: int, num2: int) -> int:\n return num1 + num2\n```\n\u261D\uFE0F which is not actually necessary\n\nYou can do this instead:\n```\nclass Solution:\n sum = add\n```\n\n**4. C**\n```\nint sum(int num1, int num2){\n return num1 + num2;\n}\n```\n**5. C#**\n```\npublic class Solution {\n public int Sum(int num1, int num2) {\n return num1 + num2;\n }\n}\n```\n**6. JavaScript**\n```\nvar sum = function(num1, num2) {\n return num1 + num2;\n};\n```\n**7. Ruby**\n```\ndef sum(num1, num2)\n num1 + num2\nend\n```\n**8. Swift**\n```\nclass Solution {\n func sum(_ num1: Int, _ num2: Int) -> Int {\n return num1 + num2\n }\n}\n```\n**9. Go**\n```\nfunc sum(num1 int, num2 int) int {\n return num1 + num2\n}\n```\n**10. Scala**\n```\nobject Solution {\n def sum(num1: Int, num2: Int): Int = {\n return num1 + num2\n }\n}\n```\n**11. Kotlin**\n```\nclass Solution {\n fun sum(num1: Int, num2: Int): Int {\n return num1 + num2\n }\n}\n```\n**12. Rust**\n```\nimpl Solution {\n pub fn sum(num1: i32, num2: i32) -> i32 {\n return num1 + num2\n }\n}\n```\n**13. PHP**\n```\nclass Solution {\n function sum($num1, $num2) {\n return $num1 + $num2;\n }\n}\n```\n**14. Typescript**\n```\nfunction sum(num1: number, num2: number): number {\n return num1 + num2\n};\n```\n**15. Racket**\n```\n(define/contract (sum num1 num2)\n (-> exact-integer? exact-integer? exact-integer?)\n (+ num1 num2)\n )\n```\n**16. Erlang**\n```\n-spec sum(Num1 :: integer(), Num2 :: integer()) -> integer().\nsum(Num1, Num2) ->\n Num1 + Num2.\n```\n**17. Elixir**\n```\ndefmodule Solution do\n @spec sum(num1 :: integer, num2 :: integer) :: integer\n def sum(num1, num2) do\n num1 + num2\n end\nend\n```\n**18. Dart**\n```\nclass Solution {\n int sum(int num1, int num2) {\n return num1 + num2;\n }\n}\n```\nThat\'s it... Upvote if you liked this solution
109,242
Add Two Integers
add-two-integers
null
Math
Easy
null
1,058
8
You recursively add/sub one ***unit*** at a time.\n\nWithout the dp-matrix, the solution is 2 ms.\nWith it, the code runs at a ***healthy*** 2,490 ms.\n```\nclass Solution {\n \n int[][] dp;\n \n public int sum(int num1, int num2) {\n dp = new int[202][202];\n for(int i = 0; i < dp.length; i++)\n Arrays.fill(dp[i], Integer.MAX_VALUE);\n \n return helper(num1, num2);\n }\n \n private int helper(int num1, int num2) {\n if(num1 == 0 && num2 == 0)\n return 0;\n \n if(dp[num1 + 100][num2 + 100] != Integer.MAX_VALUE)\n return dp[num1][num2];\n\n int answer;\n if(num1 < 0)\n answer = -1 + sum(num1 + 1, num2);\n else if(num2 < 0)\n answer = -1 + sum(num1, num2 + 1);\n else if(num1 > 0)\n answer = 1 + sum(num1 - 1, num2);\n else //if(num2 > 0)\n answer = 1 + sum(num1, num2 - 1);\n\n dp[num1 + 100][num2 + 100] = answer;\n \n return answer;\n }\n}\n```
109,246
Add Two Integers
add-two-integers
null
Math
Easy
null
2,514
28
```\nclass Solution {\n public int sum(int num1, int num2) {\n return num1 + num2;\n }\n}\n```
109,248
Add Two Integers
add-two-integers
null
Math
Easy
null
1,442
18
**Q & A:**\nQ1: Where is the source of learning bit manipulation tricks?\nA1: You can refer to the following:\n[Basics of Bit Manipulation]()\n[All about Bitwise Operations [Beginner-Intermediate]]().\n\n**End of Q & A**\n\n----\n\nLet us start with two `1-bit` binary numbers `b1` and `b2`, and we want to compute their sum by bit manipualtions, without using `+` or `-`:\n\n1. `b1 ^ b2`: sum without carry over.\n2. `b1 & b2`: carry over bit. Hence we need to shift it to the left for `1` bit to put it on the right position. e.g., `b1 = 1, b2 = 1` then `b1 & b2 = 1` and left shift `1` bit to get the corrent result: `10`. Therefore, `(b1 & b2) << 1` is the carry over.\n\nNow we obtain two new numbers: `b1\' = b1 ^ b2, b2\' = (b1 & b2) << 1`. \n\n**If we repeat the above procedure, the carry over `b2\'` will be `0` after shifting left for enough times (at most `31` times, in fact much less than that). When the carry over becomes `0`, we NO longer need to add it to `b1\'`, which is the solution already!**\n\n**The above conclusion is also correct for any two integers, not just two `1-bit` binary numbers.** Based on the conclusion, we can implement the following codes:\n\n----\n\n**Iterative versions:**\n\n```java\n public int sum(int num1, int num2) {\n while (num2 != 0) {\n int carryOver = (num1 & num2) << 1;\n num1 ^= num2; // Now num1 is the sum without carry over.\n num2 = carryOver; // num2 is the carry over now.\n }\n return num1;\n }\n```\n\n----\n\n\n**Note**: Python 3 uses different binary representation from Java or C++, so we need a `mask = 0XFFFFFFFF` to make sure that both the sum and carry over parts are with proper signs. If the result is over the upper bound `0X7FFFFFFF = 2147483647` (so should be less than `0X80000000 = 2147483648`), it is actually a negative number.\n\n```python\n def sum(self, num1: int, num2: int) -> int:\n mask = 0xFFFFFFFF\n while num2 != 0:\n num1, num2 = (num1 ^ num2) & mask, ((num1 & num2) << 1) & mask # sum w/o carry over .vs. carry over.\n return num1 if num1 < 0x80000000 else ~(num1 ^ mask)\n```\n\n----\n\n**Recursive version**:\n\n```java\n public int sum(int num1, int num2) {\n return num2 == 0 ? num1 : sum(num1 ^ num2, (num1 & num2) << 1);\n }\n```\n\n```python\n def sum(self, num1: int, num2: int) -> int:\n mask = 0XFFFFFFFF\n if num2 == 0:\n return num1 if num1 < 0X80000000 else ~(num1 ^ mask)\n return self.sum((num1 ^ num2) & mask, ((num1 & num2) << 1) & mask)\n```\n\n----\n\nFeel free to ask if you have any questions about the post, and please **upvote** if it is helpful.
109,249
Add Two Integers
add-two-integers
null
Math
Easy
null
3,116
19
```\nclass Solution {\npublic:\n int sum(int num1, int num2) {\n if (num2 == 0)\n return num1;\n \n if (num1 < 0 && num2 < 0)\n return ~sum(sum(~num1 ^ ~num2, (~num1 & ~num2) << 1), 1);\n else\n return sum(num1 ^ num2, (num1 & num2) << 1);\n }\n};\n```
109,252
Add Two Integers
add-two-integers
null
Math
Easy
null
714
6
\n```\nfunc sum(num1 int, num2 int) int { return num1 + num2 }\n```\n![a6c83c54-1d1a-4f26-8273-b687d119dd5b_1679889261.1494205.png]()
109,255
Add Two Integers
add-two-integers
null
Math
Easy
null
1,070
8
![image]()\n```\nclass Solution:\n def sum(self, num1: int, num2: int) -> int:\n return num1+num2
109,256
Root Equals Sum of Children
root-equals-sum-of-children
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.
Tree,Binary Tree
Easy
null
8,049
63
\n\n# Complexity\n- Time complexity: O(1)\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```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public boolean checkTree(TreeNode root) {\n return root.val == root.right.val + root.left.val; \n }\n}\n```\n# PLEASE UPVOTE IF IT WAS HELPFULL\n
109,264
Root Equals Sum of Children
root-equals-sum-of-children
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.
Tree,Binary Tree
Easy
null
1,979
7
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nLOL U Still opened this ......\n# Code\n```\nNOTHING HERE BRO - SORRY !\n```
109,267
Root Equals Sum of Children
root-equals-sum-of-children
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.
Tree,Binary Tree
Easy
null
4,363
11
```\nclass Solution:\n def checkTree(self, root: Optional[TreeNode]) -> bool:\n return root.val==root.left.val+root.right.val\n```\n**An upvote will be encouraging**\n
109,272
Root Equals Sum of Children
root-equals-sum-of-children
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.
Tree,Binary Tree
Easy
null
7,637
39
**As a professional with a passion for problem-solving and collaboration, I am always looking to expand my network of like-minded individuals on LinkedIn. By connecting with me, we can work together to tackle complex challenges, share ideas, and grow both professionally and personally.**\n\n**Whether you\'re an expert in your field or just starting out, I welcome connections from all backgrounds and experiences. By building a diverse and collaborative network, we can leverage our unique perspectives and skill sets to push the boundaries of what\'s possible.**\n\n**So, if you\'re interested in connecting and exploring the potential for future collaborations, please don\'t hesitate to reach out. Let\'s start a conversation and see where it takes us!**\n\n---\n\n\n\n\n\n---\n***Java***\n```\nclass Solution\n{\n public boolean checkTree(TreeNode root)\n\t{\n return root.val == root.left.val + root.right.val; // O(1)\n }\n}\n```\n\n***C++***\n```\nclass Solution\n{\npublic:\n bool checkTree(TreeNode* root)\n\t{\n if((root->left->val)+(root->right->val)==root->val) return true;\n return false;\n }\n};\n```\n\n***Python***\n```\nclass Solution:\n def checkTree(self, root: Optional[TreeNode]) -> bool:\n return root.val == (root.left.val + root.right.val)\n```\n\n***Consider upvote if useful!***
109,273
Root Equals Sum of Children
root-equals-sum-of-children
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.
Tree,Binary Tree
Easy
null
7,051
15
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nDirect Tree approach ATTACKKKKKKKKK\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```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def checkTree(self, root: Optional[TreeNode]) -> bool:\n return root.val==root.left.val + root.right.val\n```
109,277
Root Equals Sum of Children
root-equals-sum-of-children
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.
Tree,Binary Tree
Easy
null
685
6
```\nclass Solution {\npublic:\n bool checkTree(TreeNode* root) {\n queue<TreeNode*>q;\n q.push(root);\n while(!q.empty()){\n int size = q.size();\n for(int i=0;i<size;i++){\n TreeNode* curr = q.front();\n q.pop();\n int parentValue = curr->val;\n int childValue = 0;\n int child = 0;\n if(curr->left){\n q.push(curr->left);\n childValue+=curr->left->val;\n }else{\n child++;\n }\n if(curr->right){\n q.push(curr->right);\n childValue+=curr->right->val;\n }else{\n child++;\n }\n if(child==2) continue;\n if(parentValue != childValue) return false;\n }\n }\n return true;\n }\n};\n```
109,278
Root Equals Sum of Children
root-equals-sum-of-children
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.
Tree,Binary Tree
Easy
null
2,950
19
***Happy Coding..!* Feel free to ask Q\'s...**\n\n1. ***Golang Solution***\n```\n/**\n * Definition for a binary tree node.\n * type TreeNode struct {\n * Val int\n * Left *TreeNode\n * Right *TreeNode\n * }\n */\nfunc checkTree(root *TreeNode) bool {\n return root.Val == root.Left.Val + root.Right.Val\n}\n\n```\n\n2. ***Python Solution***\n```\nclass Solution(object):\n def checkTree(self, root):\n return root.val == root.left.val + root.right.val\n```\n3. ***Javascript Solution***\n```\n/**\n * @param {TreeNode} root\n * @return {boolean}\n */\n\nconst checkTree = root => root.val === (root.left.val + root.right.val);\n\n```\n\n// Tree Node\nfunction TreeNode(val, left, right) {\n this.val = (val === undefined ? 0 : val)\n this.left = (left === undefined ? null : left)\n this.right = (right === undefined ? null : right)\n}\n\n// Test Case 1\n// root = [10, 4, 6]\nlet tNode1 = new TreeNode(10);\nlet tNode2 = new TreeNode(4);\nlet tNode3 = new TreeNode(6);\n\ntNode1.left = tNode2;\ntNode1.right = tNode3;\n\nlet root = tNode1;\nconsole.log(checkTree(root)); // true\n\n\n***#happytohelpu***\n\n# ***Do upvote if you find this solution useful..***\n
109,279
Root Equals Sum of Children
root-equals-sum-of-children
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.
Tree,Binary Tree
Easy
null
2,017
10
<!-- # 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```\n/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {boolean}\n */\nvar checkTree = function(root) {\n return root.val === root.left.val + root.right.val;\n};\n```
109,283
Root Equals Sum of Children
root-equals-sum-of-children
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.
Tree,Binary Tree
Easy
null
3,618
17
```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def checkTree(self, root: Optional[TreeNode]) -> bool:\n # As per the def of binary tree node, we can compare the root value \\\n # with the TreeNode function, the root.left.val retrieves value of left node \\\n # the root.right.val retrieves value of right node. \'==\' compares two values\n if root.val == root.left.val + root.right.val: \n return True\n else:\n return False\n```
109,296
Root Equals Sum of Children
root-equals-sum-of-children
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.
Tree,Binary Tree
Easy
null
5,828
19
```\nclass Solution:\n def checkTree(self, root: Optional[TreeNode]) -> bool:\n return root.val == (root.left.val + root.right.val)
109,298
Root Equals Sum of Children
root-equals-sum-of-children
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.
Tree,Binary Tree
Easy
null
4,092
13
```\nclass Solution {\npublic:\n bool checkTree(TreeNode* root) {\n if(root->left->val+root->right->val==root->val){\n return true;\n }\n return false;\n }\n};\n```
109,301
Root Equals Sum of Children
root-equals-sum-of-children
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.
Tree,Binary Tree
Easy
null
1,878
13
```\nclass Solution {\npublic:\n bool checkTree(TreeNode* root) {\n return root->val == (root->left->val+root->right->val);\n }\n};\n```
109,304
Root Equals Sum of Children
root-equals-sum-of-children
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.
Tree,Binary Tree
Easy
null
1,795
11
Let me know if you have any doubts. I try to answer/help.\n\nPlease upvote if you liked the solution.\n\n```\nvar checkTree = function(root) {\n return root.val === root.left.val + root.right.val;\n};\n```
109,306