question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fraction-addition-and-subtraction
|
C++ || Simple
|
c-simple-by-abhinav_singh_01-l3s1
|
class Solution {\npublic:\n string fractionAddition(string exp) {\n int nu=0, du=1;\n int i=0, n=exp.size();\n int sign=1;\n whil
|
Abhinav_Singh_01
|
NORMAL
|
2022-07-13T08:49:44.910084+00:00
|
2022-07-13T08:49:44.910111+00:00
| 717 | false |
class Solution {\npublic:\n string fractionAddition(string exp) {\n int nu=0, du=1;\n int i=0, n=exp.size();\n int sign=1;\n while(i<n)\n {\n int x=0,y=0;\n if(exp[i]==\'+\') sign=1, i=i+1;\n else if(exp[i]==\'-\') sign= -1, i=i+1;\n while( i<n and exp[i]>=\'0\' and exp[i]<=\'9\' )x= 10*x+exp[i++]-\'0\';\n \n i++;\n while(i<n and exp[i]>=\'0\' and exp[i]<=\'9\' )\n y=y*10 + exp[i++]-\'0\';\n \n x*=sign;\n \n nu= nu*y+du*x;\n du*=y;\n \n \n if(!nu)\n {\n du=1;\n }\n else\n {\n int gcd= __gcd(abs(nu),du);\n nu/=gcd;\n du/=gcd;\n }\n \n \n }\n return to_string(nu)+"/"+to_string(du);\n }\n};
| 2 | 0 |
['C']
| 0 |
fraction-addition-and-subtraction
|
C++ with comments
|
c-with-comments-by-chase1991-u5ih
|
\nclass Solution {\npublic:\n string fractionAddition(string expression) {\n int nom = 0, denom = 1, size = expression.size();\n for (int i = 0
|
chase1991
|
NORMAL
|
2021-03-13T23:47:40.110636+00:00
|
2021-03-13T23:47:40.110678+00:00
| 150 | false |
```\nclass Solution {\npublic:\n string fractionAddition(string expression) {\n int nom = 0, denom = 1, size = expression.size();\n for (int i = 0, j = 0; i < size;)\n {\n while (j < size && expression[j] != \'/\')\n {\n ++j; // find the index of slash \'/\' so we can get the nominator\n }\n \n int slashInd = j;\n while (j < size && expression[j] != \'+\' && expression[j] != \'-\')\n {\n ++j; // find the next \'+\' or \'-\' so we can get the denominator\n }\n \n int end = j, curNom = stoi(expression.substr(i, slashInd - i));\n int curDenom = stoi(expression.substr(slashInd + 1, end - slashInd - 1));\n auto sum = addAndNorm(nom, denom, curNom, curDenom); // add the fractions \n \n nom = sum.first;\n denom = sum.second; // update the latest nominator and denominator\n i = j;\n }\n \n return to_string(nom) + "/" + to_string(denom); // return the result\n }\n\nprivate:\n pair<int, int> addAndNorm(int nom, int denom, int curNom, int curDenom)\n {\n int sumNom = nom * curDenom + curNom * denom;\n int sumDenom = denom * curDenom; // first get the reducible nominator/denominator\n for (int n = min(abs(sumNom), abs(sumDenom)); n > 1; --n)\n {\n if (sumNom % n == 0 && sumDenom % n == 0)\n { // find the maximum common factor of the nominator and denominator\n sumNom /= n;\n sumDenom /= n;\n break;\n }\n }\n \n return {sumNom, sumNom == 0 ? 1 : sumDenom}; // return the reduced format\n }\n};\n```
| 2 | 0 |
[]
| 0 |
fraction-addition-and-subtraction
|
C++ code
|
c-code-by-divyam_sinha-4a7x
|
The idea is to first split the string with \'+\' and \'-\' operators \nNow extracting value before \'/\' and value after \'/\' and store it in numerator and den
|
divyam_sinha
|
NORMAL
|
2021-02-06T11:01:53.647797+00:00
|
2021-02-06T11:20:54.991726+00:00
| 257 | false |
The idea is to first split the string with \'+\' and \'-\' operators \nNow extracting value before \'/\' and value after \'/\' and store it in numerator and denominator vector \nFind LCM of denominator and store it in lcm \nNow lcm / denominator[i] gives us the multiply factor which needs to be multiplied to numerator \nIterate through numerator , multiply the multiply factor to numerator and add it to sum ; \nNow to simplify find HCF or GCD of abs(lcm) and abs(sum) and store it as divFact ;\nsum = sum / divFact and lcm = lcm / divFact \nans = to_string(sum) + \'/\' + to_string(lcm) ;\n\n\tint gcd(int a , int b){\n if(b == 0){\n return a ; \n }\n return gcd(b , a%b) ; \n }\n \n int LCM(vector<int> Denominator){\n int lcm = 1 ; \n for(int i = 0 ; i < Denominator.size() ; i++){\n lcm = lcm * Denominator[i] / gcd(lcm , Denominator[i]) ; \n }\n return lcm ; \n }\n \n int to_int(string Expression){\n int sign = 1 ;\n int i = 0;\n if(Expression[0] == \'-\'){\n sign = -1 ;\n i = 1 ; \n }\n int number = 0 ; \n while(i < Expression.size()){\n number = number * 10 + (Expression[i] - \'0\') ; \n i++ ; \n }\n number = number * sign ;\n return number ;\n }\n \n vector<string> splitValues(string s){\n string temp ;\n vector<string> splitExpression ;\n int n = s.size() ; \n for(int i = 0 ; i < n ; i++){\n while( i < n and s[i] != \'+\' and s[i] != \'-\'){\n temp+=s[i] ; \n i++;\n }\n if(i < n and s[i] == \'-\'){\n if(temp.size() > 0)\n splitExpression.push_back(temp) ;\n temp = \'-\' ;\n continue ; \n }\n else if(i<n and s[i] == \'+\'){\n if(temp.size() > 0)\n splitExpression.push_back(temp) ;\n temp.erase() ; \n continue ;\n }\n }\n if(temp.size() > 0)\n splitExpression.push_back(temp) ; \n return splitExpression ;\n }\n \n string fractionAddition(string expression) {\n vector<int> Numerator ; \n vector<int> Denominator ; \n \n vector<string> splitExpression = splitValues(expression) ;\n for(auto x : splitExpression){\n int idx = x.find(\'/\') ; \n string firstHalf = x.substr(0,idx) ;\n string secondHalf = x.substr(idx + 1 , 40) ; \n cout << firstHalf << " " << secondHalf << endl <<endl ;\n Numerator.push_back(to_int(firstHalf)) ; \n Denominator.push_back(to_int(secondHalf)) ;\n }\n int lcm = LCM(Denominator) ; \n //cout << lcm <<endl ;\n int sum = 0 ; \n for(int i = 0 ; i < Denominator.size() ; i++){\n int val = lcm / Denominator[i] ; \n sum += (val * Numerator[i]) ; \n }\n //cout << sum << endl ; \n int divFact = abs(gcd(abs(sum) , abs(lcm))) ;\n //cout << divFact << endl ; \n sum = sum / divFact ; \n lcm = lcm / divFact ; \n string ans = to_string(sum) + \'/\' + to_string(lcm) ; \n return ans ;\n }\n\t\n\t\n\t// Happy Coding
| 2 | 0 |
['Math']
| 0 |
fraction-addition-and-subtraction
|
Java OOP solution (5ms, faster than 90%)
|
java-oop-solution-5ms-faster-than-90-by-60hd3
|
I think it\'s self-self-explanatory.\n\n\nclass Solution {\n static class Fraction {\n private int d;\n private int n;\n \n Fract
|
littlecreek
|
NORMAL
|
2021-01-24T19:47:13.864515+00:00
|
2021-01-24T19:47:13.864553+00:00
| 308 | false |
I think it\'s self-self-explanatory.\n\n```\nclass Solution {\n static class Fraction {\n private int d;\n private int n;\n \n Fraction() {\n d = 1; \n }\n \n Fraction(int n, int d) {\n if ( d < 0) {\n d = -d;\n n = -n;\n }\n this.d = d;\n this.n = n;\n }\n \n private int gcd(int a, int b) {\n if (b == 0) return a;\n return gcd(b, a%b);\n }\n \n public Fraction add(Fraction other) {\n int d = this.d * other.d;\n // TODO overflow?\n int n = this.n * other.d + other.n * this.d;\n int g = gcd(n, d);\n n /= g;\n d /= g;\n return new Fraction(n, d);\n }\n \n public static Fraction fromString(String s) {\n String[] arr = s.split("/");\n return new Fraction(Integer.valueOf(arr[0]), Integer.valueOf(arr[1]));\n }\n \n @Override\n public String toString() {\n return n + "/" + d;\n }\n }\n \n public String fractionAddition(String expression) {\n Fraction fraction = new Fraction();\n List<String> list = new ArrayList<>();\n \n int prev = 0;\n for (int i = 0; i <= expression.length(); i++) {\n if (i == expression.length() \n || i > 0 && ( expression.charAt(i) == \'+\' || expression.charAt(i) == \'-\')) {\n list.add(expression.substring(prev, i));\n prev = i;\n }\n }\n \n \n for (String s : list) {\n fraction = fraction.add(Fraction.fromString(s));\n }\n return fraction.toString();\n }\n}\n```
| 2 | 0 |
[]
| 1 |
fraction-addition-and-subtraction
|
C++ Simple 100% Time and Space Solution
|
c-simple-100-time-and-space-solution-by-s4ljz
|
\nclass Solution {\npublic:\n int gcd(int a, int b){\n if (b == 0)\n return a;\n return gcd(b, a % b); \n\n }\n string fractio
|
rom111
|
NORMAL
|
2020-10-10T09:31:21.400068+00:00
|
2020-10-10T09:31:21.400110+00:00
| 379 | false |
```\nclass Solution {\npublic:\n int gcd(int a, int b){\n if (b == 0)\n return a;\n return gcd(b, a % b); \n\n }\n string fractionAddition(string exp) {\n vector<int>num,den;\n int out=1;\n int n=exp.length();\n for(int i=0;i<n;i++){\n if(exp[i]==\'-\'){\n out=0;\n i++;\n }else if(exp[i]==\'+\'){\n out=1;\n i++;\n }\n string a="";\n while(i<n && exp[i]!=\'/\'){\n a+=exp[i];\n i++;\n }\n // cout << a << "/";\n if(out==0){\n num.push_back(-stoi(a));\n }else{\n num.push_back(stoi(a));\n }\n if(exp[i]==\'/\'){\n i++;\n }\n a="";\n while(i<n && exp[i]!=\'-\' && exp[i]!=\'+\'){\n a+=exp[i];\n i++;\n }\n // cout << a << "\\n";\n den.push_back(stoi(a));\n i--;\n }\n int proden=1;\n for(int i=0;i<den.size();i++){\n proden*=den[i];\n }\n int sum=0;\n for(int i=0;i<den.size();i++){\n int a=proden/den[i];\n sum+=(num[i]*a);\n }\n if(abs(sum)%proden==0){\n return to_string(sum/proden)+"/1";\n }\n int a=gcd(sum,proden);\n if(proden<0 || sum<0){\n return "-"+to_string(abs(sum/a))+"/"+to_string(abs(proden/a));\n }\n return to_string(sum/a)+"/"+to_string(proden/a);\n }\n};\n```
| 2 | 1 |
['C']
| 0 |
fraction-addition-and-subtraction
|
C++ | Stringstream | Clean code
|
c-stringstream-clean-code-by-wh0ami-1zu1
|
Intuition:\nParse the numbers using stringstream and peform operation on 2 fractions at a time and keep storing the result in first one.\n\nSolution:\n\n\nclass
|
wh0ami
|
NORMAL
|
2020-05-23T14:18:32.766934+00:00
|
2020-05-23T14:22:39.547885+00:00
| 140 | false |
**Intuition:**\nParse the numbers using stringstream and peform operation on 2 fractions at a time and keep storing the result in first one.\n\n**Solution:**\n\n```\nclass Solution {\n void addfraction(int &a, int &b, int c, int d) {\n int nume = a*d + b*c;\n int deno = b*d;\n int gcd = __gcd(abs(nume), abs(deno));\n a = nume/gcd; b = deno/gcd;\n }\npublic:\n string fractionAddition(string expression) {\n \n stringstream ss(expression);\n char op;\n int a, b, c, d;\n \n ss >> a; ss >> op; ss >> b;\n while (ss >> c) {\n ss >> op; ss >> d;\n addfraction(a, b, c, d);\n }\n \n string res;\n res = to_string(a) + "/" + to_string(b);\n return res;\n }\n};\n```
| 2 | 0 |
[]
| 0 |
fraction-addition-and-subtraction
|
Java O(n) solution
|
java-on-solution-by-losty-aes7
|
\nclass Solution {\n public String fractionAddition(String expression) {\n expression = expression.replaceAll("-", "\\\\+-");\n String[] fracti
|
losty
|
NORMAL
|
2020-04-14T02:25:45.048774+00:00
|
2020-04-14T02:25:45.048812+00:00
| 308 | false |
```\nclass Solution {\n public String fractionAddition(String expression) {\n expression = expression.replaceAll("-", "\\\\+-");\n String[] fractions = expression.split("\\\\+");\n \n List<int[]> fr = new ArrayList();\n \n int commonDenom = 1;\n \n for (String s : fractions) {\n if (s.length() == 0)\n continue;\n \n String[] a = s.split("/");\n int n = Integer.parseInt(a[0]);\n int d = Integer.parseInt(a[1]);\n \n if (commonDenom % d != 0)\n commonDenom *= d;\n fr.add(new int[]{n, d});\n }\n \n int sum = 0;\n for (int[] a : fr) {\n sum += (a[0] * commonDenom / a[1]);\n }\n\n int gcdSumDenom = gcd(Math.abs(sum), commonDenom);\n sum /= gcdSumDenom;\n commonDenom /= gcdSumDenom;\n \n return "" + sum + "/" + (commonDenom == 0 ? 1 : commonDenom);\n }\n \n public int gcd(int a, int b) {\n while (b != 0) {\n int t = b;\n b = a % b;\n a = t;\n }\n return a;\n }\n}\n```
| 2 | 0 |
[]
| 0 |
fraction-addition-and-subtraction
|
Easy Simple Java + detail explanation
|
easy-simple-java-detail-explanation-by-s-ismh
|
Full detail explanation: https://medium.com/@hch.hkcontact/goldman-sachs-top-50-leetcode-questions-q9-fraction-addition-and-subtraction-eed82a3e3fd3\n\nSteps:\n
|
savehch
|
NORMAL
|
2020-02-26T07:45:56.728259+00:00
|
2020-02-26T07:52:38.546623+00:00
| 679 | false |
Full detail explanation: https://medium.com/@hch.hkcontact/goldman-sachs-top-50-leetcode-questions-q9-fraction-addition-and-subtraction-eed82a3e3fd3\n\nSteps:\nLoop the character (ch) in the given string\nCase 1:if not met "/"\n- add ch to string\n\nCase 2: if not met "/" & meet "/"\n- parse string to numerator\n- make the boolean that met "/" be true\n\nCase 3: if met "/" & meet "+" or "-"\n- parse string to denom\n- make new fraction\n- if has stored fraction, compute them together to get a fraction and store it\n- make the boolean that met "/" be false\n\nCase 4: if met "/"\n- add ch to string\n\nreturn the last computed fraction as string\n\nPerformance:\n- time complexity: O(n), n is no. of characters of the input string\n- space complexity: O(m), m is no. of characters of one of the fractions of input string\n\n```\nclass Fraction{\n int numerator;\n int denominator;\n \n public Fraction(int numerator, int denominator){\n this.numerator=numerator;\n this.denominator=denominator;\n }\n \n public String toString(){\n return String.valueOf(numerator)+"/"+denominator;\n }\n}\n\n\n\nclass Solution {\n \n private int hcf(int a, int b){\n if(b==0) return a;\n return hcf(b, a%b);\n }\n \n private Fraction computeFraction(Fraction f1, Fraction f2){\n int curNumerator = f1.numerator * f2.denominator + f2.numerator * f1.denominator;\n int curDenominator = f1.denominator * f2.denominator;\n if(curNumerator==0) return new Fraction(0,1); \n int bigger = Math.max(Math.abs(curNumerator), Math.abs(curDenominator));\n int smaller = Math.min(Math.abs(curNumerator), Math.abs(curDenominator));\n int hcf = hcf(bigger, smaller);\n return new Fraction(curNumerator/hcf, curDenominator/hcf);\n\n }\n \n \n public String fractionAddition(String expression) {\n\n char[] ar = expression.toCharArray();\n int i=0;\n int n = ar.length;\n \n Fraction stored = null;\n boolean positive = true;\n int numerator = 0;\n int denominator = 0;\n StringBuilder sb = new StringBuilder();\n \n boolean metSlash = false;\n \n while(i<n){\n char ch = ar[i];\n if(!metSlash&&ch==\'/\'){\n numerator = Integer.parseInt(sb.toString());\n sb=new StringBuilder();\n metSlash=true;\n }else if(!metSlash){ \n sb.append(ch);\n }else if(i==n-1||(metSlash&&(ch==\'+\'||ch==\'-\'))){\n if(i==n-1) sb.append(ch);\n denominator = Integer.parseInt(sb.toString());\n Fraction curFac = new Fraction(numerator, denominator);\n if(stored!=null) curFac=computeFraction(stored, curFac);\n stored=curFac;\n sb=new StringBuilder();\n sb.append(ch);\n metSlash=false;\n }else if(metSlash){\n sb.append(ch);\n }\n i++;\n }\n \n return stored.toString();\n }\n}\n```
| 2 | 0 |
['Java']
| 0 |
fraction-addition-and-subtraction
|
Straightforward and short Python solution using regex and `fractions` module
|
straightforward-and-short-python-solutio-ksnf
|
With the fractions module, doing rational number arithmetic becomes really trivial.\n\n\nclass Solution(object):\n def fractionAddition(self, expression):\n
|
yangshun
|
NORMAL
|
2017-05-21T03:27:53.907000+00:00
|
2017-05-21T03:27:53.907000+00:00
| 451 | false |
With the `fractions` module, doing rational number arithmetic becomes really trivial.\n\n```\nclass Solution(object):\n def fractionAddition(self, expression):\n """\n :type expression: str\n :rtype: str\n """\n import re\n from fractions import Fraction\n # Append + to start if first fraction is positive for easier parsing.\n expression = ('+' + expression) if expression[0] != '-' else expression\n splitted = re.split('([-|\\+]\\d+\\/\\d+)', expression)\n splitted = [fragment for fragment in splitted if fragment.strip() != '']\n \n def parse_fraction(fraction):\n sign = fraction[0]\n numer, denom = [int(part) for part in fraction[1:].split('/')]\n return Fraction(numer if sign == '+' else -numer, denom)\n \n result = 0\n for fraction in [parse_fraction(part) for part in splitted]:\n result += fraction\n return "{}/{}".format(result.numerator, result.denominator)\n \n```
| 2 | 0 |
[]
| 0 |
fraction-addition-and-subtraction
|
One-liner
|
one-liner-by-stefanpochmann-8acr
|
Easy peasy.\n\ndef fraction_addition(expression)\n eval(expression.gsub(/\\d+/, 'Rational(\\0)')).to_s\nend\n
|
stefanpochmann
|
NORMAL
|
2017-05-21T08:55:52.923000+00:00
|
2017-05-21T08:55:52.923000+00:00
| 425 | false |
Easy peasy.\n```\ndef fraction_addition(expression)\n eval(expression.gsub(/\\d+/, 'Rational(\\0)')).to_s\nend\n```
| 2 | 0 |
[]
| 0 |
fraction-addition-and-subtraction
|
C#
|
c-by-adchoudhary-eqjh
|
Code
|
adchoudhary
|
NORMAL
|
2025-02-24T04:19:19.441614+00:00
|
2025-02-24T04:19:19.441614+00:00
| 5 | false |
# Code
```csharp []
using System.Text.RegularExpressions;
public class Solution {
public string FractionAddition(string expression)
{
int numerator = 0, denominator = 1;
Regex regex = new Regex(@"([+-]?\d+)\/(\d+)");
MatchCollection matches = regex.Matches(expression);
foreach (Match match in matches)
{
int num = int.Parse(match.Groups[1].Value);
int den = int.Parse(match.Groups[2].Value);
numerator = numerator * den + num * denominator;
denominator *= den;
int gcdVal = GCD(Math.Abs(numerator), denominator);
numerator /= gcdVal;
denominator /= gcdVal;
}
return $"{numerator}/{denominator}";
}
private int GCD(int a, int b)
{
while (b != 0)
{
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}
```
| 1 | 0 |
['C#']
| 0 |
fraction-addition-and-subtraction
|
Easy Brute-Force Approach for beginners
|
easy-brute-force-approach-for-beginners-bzzjy
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
RAMANA_GANTHAN_S
|
NORMAL
|
2025-01-09T08:00:45.717171+00:00
|
2025-01-09T08:00:45.717171+00:00
| 18 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def fractionAddition(self, expression: str) -> str:
from fractions import Fraction
if expression[0]!='-':
expression='+'+expression
nums=expression.split('+')
new=[]
for i in nums:
temp=i.split("-")
new+=temp
operations=[]
for i in expression:
if i=='+' or i=='-':
operations.append(i)
res=[]
op=0
ans=0
for f in new:
if f != '':
dn=f.split('/')
n=Fraction(int(dn[0]),int(dn[1]))
if operations[op]=='-':
ans-=n
else:
ans+=n
op+=1
if len(str(ans))==1:
return str(ans)+'/1'
elif str(ans)[0]=='-' and len(str(ans))==2:
return str(ans)+'/1'
else:
return str(ans)
```
| 1 | 0 |
['Python3']
| 0 |
fraction-addition-and-subtraction
|
Best C++ Code (Beats 100%)
|
best-c-code-beats-100-by-souravsinghal20-e32u
|
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
|
souravsinghal2004
|
NORMAL
|
2024-10-02T07:43:04.068508+00:00
|
2024-10-02T07:43:04.068525+00:00
| 0 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n using int2=pair<int, int>;\n void print(auto& f){\n for(auto& [x, y]: f) cout<<"("<<x<<","<<y<<")";\n cout<<endl;\n }\n\n vector<int2> convert(string& expression){\n vector<int2> fraction;\n int sz=expression.size(), x=0, sgn=1;\n char c=expression[0];\n switch(c){\n case \'+\':break;\n case \'-\': sgn=-1; break;\n default: x=c-\'0\';\n }\n int prev=0;\n for(int i=1; i<sz; i++){\n c=expression[i];\n while(c>=\'0\'){\n x=10*x+(c-\'0\');\n if (i==sz-1) break;\n c=expression[++i];\n // cout<<x<<", ";\n }\n switch(c){\n case \'+\':\n fraction.emplace_back(prev, x);\n sgn=1; \n x=0;\n break;\n case \'-\':\n fraction.emplace_back(prev, x); \n sgn=-1; \n x=0;\n break;\n case \'/\':\n prev=x*sgn;\n x=0;\n } \n }\n // dealing with i=sz-1\n fraction.emplace_back(prev, x);\n return fraction;\n }\n int2 add(int2& x, int2& y){\n auto [xp, xq]=x;\n auto [yp, yq]=y;\n long long q=xq*yq;\n long long p=xp*yq+xq*yp;\n long long g=gcd(p, q);\n return {p/g, q/g};\n }\n \n string fractionAddition(string& expression) {\n auto fraction=convert(expression);\n // print(fraction);\n int fz=fraction.size();\n int2 ans={0, 1};\n for(auto& f: fraction){\n ans=add(ans, f);\n }\n string s=to_string(ans.first)+"/"+to_string(ans.second);\n return s;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
fraction-addition-and-subtraction
|
Beats 100% users in C++.
|
beats-100-users-in-c-by-caffeinekeyboard-grky
|
Intuition\nThe problem involves adding and subtracting fractions from an expression. Fractions consist of a numerator and a denominator, and to perform addition
|
caffeinekeyboard
|
NORMAL
|
2024-09-10T11:58:50.119971+00:00
|
2024-09-10T12:00:05.654724+00:00
| 4 | false |
# Intuition\nThe problem involves adding and subtracting fractions from an expression. Fractions consist of a numerator and a denominator, and to perform addition or subtraction, we can use the common denominator method. After performing operations on the fractions, we reduce the resulting fraction to its simplest form by dividing both the numerator and denominator by their greatest common divisor (GCD).\n\n\n\n# Approach\n1. Parse each fraction from the input string. A fraction has the form `a/b`, where `a` is the numerator and `b` is the denominator.\n2. Identify the sign (`+` or `-`) before each fraction to determine whether it should be added or subtracted.\n3. Use the formula for adding/subtracting fractions with different denominators: \n $$ \\frac{a}{b} \\pm \\frac{c}{d} = \\frac{a \\cdot d \\pm c \\cdot b}{b \\cdot d} $$\n4. After each operation, reduce the resulting fraction by dividing both the numerator and denominator by their GCD.\n5. Ensure the denominator is positive. If the denominator is negative, multiply both the numerator and denominator by `-1` to keep the denominator positive.\n6. Finally, return the resulting fraction in string format as `"numerator/denominator"`.\n\n# Complexity\n- **Time complexity:** \n Parsing the expression involves scanning each character, resulting in a complexity of $$O(n)$$, where $$n$$ is the length of the input string. Each GCD operation takes $$O(\\log(\\min(a,b)))$$, but this is dominated by the linear scan.\n\n- **Space complexity:** \n The space complexity is $$O(1)$$, as the space used is constant, not dependent on the input size.\n\n# Code\n```cpp\nclass Solution {\npublic:\n // Helper function to reduce the fraction by its GCD\n void reduceFraction(int& numerator, int &denominator)\n {\n int greatestCommonDivisor = __gcd(numerator, denominator);\n numerator /= greatestCommonDivisor;\n denominator /= greatestCommonDivisor;\n // Ensure the denominator is positive\n if(denominator < 0)\n {\n numerator *= -1;\n denominator *= -1;\n }\n }\n \n // Function to process the fraction addition expression\n string fractionAddition(string expression) {\n int numerator = 0; // Initialize numerator to 0\n int denominator = 1; // Initialize denominator to 1 (for a valid fraction)\n bool positiveFlag = true; // To track the sign of each fraction\n \n // Loop through the input expression\n for(int index = 0 ; index < expression.length() ; )\n {\n // Check for numbers in the expression (i.e., the numerator)\n if(expression[index] >= \'0\' && expression[index] <= \'9\')\n {\n int currNumerator = 0;\n // Parse the numerator of the fraction\n while(expression[index] != \'/\') {\n currNumerator = 10 * currNumerator + (expression[index] - \'0\');\n index++;\n }\n index++; // Skip the \'/\'\n \n // Parse the denominator of the fraction\n int currDenominator = 0;\n while(expression[index] >= \'0\' && expression[index] <= \'9\') {\n currDenominator = 10 * currDenominator + (expression[index] - \'0\');\n index++;\n }\n \n // Update the numerator and denominator based on the current fraction\n if(positiveFlag) {\n numerator = numerator * currDenominator + currNumerator * denominator;\n } else {\n numerator = numerator * currDenominator - currNumerator * denominator;\n }\n denominator *= currDenominator;\n \n // Reduce the fraction to its simplest form\n reduceFraction(numerator, denominator);\n }\n else {\n // Handle signs in the expression\n if(expression[index] == \'+\')\n positiveFlag = true;\n else\n positiveFlag = false;\n index++;\n }\n }\n \n // Return the final reduced fraction in string format\n return to_string(numerator) + \'/\' + to_string(denominator);\n }\n};\n
| 1 | 0 |
['C++']
| 0 |
fraction-addition-and-subtraction
|
Efficiently Adding Fractions: Parsing and Simplifying in One Pass
|
efficiently-adding-fractions-parsing-and-z7zh
|
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem involves combining fractions from a string expression by parsing each fract
|
nilanshu_kumar81
|
NORMAL
|
2024-08-24T17:21:43.777225+00:00
|
2024-08-24T17:21:43.777258+00:00
| 10 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves combining fractions from a string expression by parsing each fraction and then adding or subtracting them using a common denominator. As you process each fraction, you adjust the cumulative result by updating the numerator and denominator accordingly. Finally, simplify the result by reducing it to its simplest form using the greatest common divisor (GCD).\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe problem involves evaluating an expression composed of fractions connected by + or - signs, e.g., -1/2+1/3-1/4. The goal is to return the result in its simplest form as a fraction.\n\n1. Initialize Variable:\n - `nume` (numerator) is initialized to `0`. This will hold the cumulative numerator as we process the fractions.\n - `deno` (denominator) is initialized to `1`. This will hold the cumulative denominator as we process the fractions.\n - `i` is the index for traversing the string, and `n` is the length of the input string.\n2. The main loop iterates through the entire expression string.\n3. Identify and Parse Each Fraction:\n 1. Sign Detection:\n - Check if the current character is $$\'-\' or \'+\'$$. If it\'s $$\'-\'$$, set `isNeg` to $$true$$, indicating that the upcoming fraction will be negative.\n - If the character is a sign, increment `i` to $$skip$$ it.\n 2. Parse Numerator:\n - Build the numerator by iterating over the digits until you encounter the division character `\'/\'`. Convert the character digits to an integer (`curNum`).\n 3. Parse Denominator:\n - Skip the division character and build the denominator by iterating over the digits after the `\'/\'`. Convert these digits into an integer (`curDen`).\n 4. Apply Sign:\n - If the fraction is negative (`isNeg == true`), multiply curNum by $$-1$$.\n4. Update the Cumulative Fraction:\n 1. Use this formula to add fractions:\n - `new\xA0numerator=nume X curDen + curNum X deno`\n - `new\xA0denominator=deno\xD7curDen`\n 2. Update` nume` and `deno` with the new values.\n5. Simplify the Resulting Fraction:\n - Compute the Greatest Common Divisor (`GCD`) of the numerator and denominator using the built-in $$__gcd function$$.\n - Divide both the numerator and denominator by their GCD to reduce the fraction to its simplest form.\n6. Return the Result:\n - Convert the simplified numerator and denominator to a string in the form `"nume/deno"` and return it.\n\n# Example Walkthrough\nConsider the expression $$-1/2+1/3-1/4$$:\n- Start with `nume = 0, deno = 1`.\n- Process $$-1/2$$:\n - $$curNum = -1, curDen = 2$$.\n - Update $$nume$$ = 0 * 2 + (-1) * 1 = -1.\n - Update $$deno$$ = 1 * 2 = 2.\n- Process` +1/3`:\n - $$curNum = 1, curDen = 3$$.\n - Update $$nume$$ = -1 * 3 + 1 * 2 = -3 + 2 = -1.\n - Update $$deno$$ = 2 * 3 = 6.\n- Process -1/4:\n - $$curNum = -1, curDen = 4$$.\n - Update $$nume$$ = -1 * 4 + (-1) * 6 = -4 + (-6) = -10.\n - Update $$deno$$ = 6 * 4 = 24.\n- Simplify:\n - $$GCD = 2$$.\n - $$nume$$ = -10 / 2 = -5, $$deno$$ = 24 / 2 = 12.\n- `Result: "-5/12"`.\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string fractionAddition(string expression) {\n int nume = 0;\n int deno = 1;\n\n int i = 0;\n int n = expression.size();\n while(i < n){\n int curNum = 0;\n int curDen = 0;\n\n bool isNeg = (expression[i] == \'-\');\n \n if(expression[i]== \'+\' || expression[i] == \'-\'){\n i++;\n }\n\n // Build the currName\n while(i < n && isdigit(expression[i])){\n int val = expression[i] - \'0\';\n curNum = (curNum*10) + val;\n i++;\n }\n\n i++; // numerator / division // skiping the divisor character\n\n if(isNeg == true) curNum *= -1;\n\n // Build the currDeno\n while(i < n && isdigit(expression[i])){\n int val = expression[i] - \'0\';\n curDen = (curDen*10) + val;\n i++;\n }\n\n nume = nume * curDen + curNum * deno;\n deno = deno * curDen;\n }\n int GCD = abs(__gcd(nume,deno));\n\n // - 3 / 6 // GCD : 3\n nume /= GCD;\n deno /= GCD;\n return to_string(nume) + "/" + to_string(deno);\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
fraction-addition-and-subtraction
|
While loop + Build a Parser (explanation + code comments)
|
while-loop-build-a-parser-explanation-co-shcx
|
Intuition\n Describe your first thoughts on how to solve this problem. \nWe can parse the string with a while loop:\n1. Before we start the while loop, get the
|
vikktour
|
NORMAL
|
2024-08-24T02:32:19.483155+00:00
|
2024-08-24T02:32:19.483185+00:00
| 5 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can parse the string with a while loop:\n1. Before we start the while loop, get the first fraction. This will be the overall fraction that we will add to / subtract from\n2. Keep looping as we get a new operand and next fraction\n3. Combine and simplify the fraction\n\n# Complexity\n- Time complexity: O(N)\nWe parse through the string once and perform add/subtract for each operation.\n\n- Space complexity: O(N) or O(1)\nThe answer can be just as long as the input (or half as long)\nEx: 1/2 - 1/4 = -1/8\nBut in this case, the numerator / denominator are <= 10 so the answer is going to remain small ~ O(1). We are also simplifying the fraction at each operation (rather than at the end), so the denominator won\'t get absurdly large.\n\n# Code\n```python3 []\nclass Solution:\n\n def __init__(self):\n self.operators = ["+","-"]\n self.idx = 0\n\n def getNumerator(self, expression) -> str:\n numerator = ""\n start = self.idx\n while not(expression[self.idx] == "/"):\n self.idx += 1\n numerator = expression[start:self.idx]\n return numerator\n \n def getDenominator(self, expression) -> str:\n denominator = ""\n start = self.idx\n while (self.idx < len(expression)) and not((expression[self.idx] in self.operators)):\n self.idx += 1\n denominator = expression[start:self.idx]\n return denominator\n\n # Returns the next fraction in form of (numerator, denominator)\n def getFraction(self, expression) -> (int,int):\n numerator = int(self.getNumerator(expression))\n self.idx += 1 # Go pass the "/"\n denominator = int(self.getDenominator(expression))\n return (numerator, denominator)\n\n\n def combineFract(self, fraction1, fraction2, operator) -> (int,int):\n num1,den1 = fraction1[0],fraction1[1]\n num2,den2 = fraction2[0],fraction2[1]\n \n # Get a common denominator so we can combine them\n commonDenom = den1 * den2\n num1 = num1 * den2\n num2 = num2 * den1\n\n if operator == "+":\n numerator = num1 + num2\n else:\n numerator = num1 - num2\n \n # Simplify the fraction\n greatestCommonDivisor = gcd(abs(numerator), commonDenom)\n numerator = numerator // greatestCommonDivisor\n denominator = commonDenom // greatestCommonDivisor\n\n return (numerator, denominator)\n\n def fractionAddition(self, expression: str) -> str:\n lenExpression = len(expression)\n \n # Get first fraction\n fraction = self.getFraction(expression)\n\n while True:\n # If there are no new operators, don\'t need to do anymore add/subtract\n if self.idx >= len(expression):\n break\n\n # Get operator\n operator = expression[self.idx]\n self.idx += 1\n\n # Get next fraction\n nextFraction = self.getFraction(expression)\n\n # Combine them\n fraction = self.combineFract(fraction,nextFraction,operator)\n \n return str(fraction[0]) + "/" + str(fraction[1])\n```
| 1 | 0 |
['Python3']
| 0 |
fraction-addition-and-subtraction
|
Fraction addition and subtraction.
|
fraction-addition-and-subtraction-by-nar-9xun
|
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
|
Narendra_Sai
|
NORMAL
|
2024-08-23T23:58:49.772070+00:00
|
2024-08-23T23:58:49.772090+00:00
| 2 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public String fractionAddition(String expression) {\n int nume=0;\n int deno=1;\n char[]ex=expression.toCharArray();\n int i=0;\n while(i<ex.length){\n int currNume=0;\n int currDeno=0;\n boolean isNeg=(ex[i]==\'-\');\n if(ex[i]==\'+\'){\n i++;\n }\n else if(ex[i]==\'-\'){\n isNeg=true;\n i++;\n }\n while(i<ex.length && Character.isDigit(ex[i])){\n int val=ex[i]-\'0\';\n currNume=(currNume*10)+val;\n i++;\n }\n i++;// to skip the devisor char \'/\';\n if(isNeg){\n currNume=-currNume;\n }\n\n while(i<ex.length && Character.isDigit(ex[i])){\n int val=ex[i]-\'0\';\n currDeno=(currDeno*10)+val;\n i++;\n }\n nume=nume*currDeno+currNume*deno;\n deno=deno*currDeno;\n }\n int gcd= Math.abs(findGCD(nume,deno));\n nume/=gcd;\n deno/=gcd;\n return Integer.toString(nume)+"/"+Integer.toString(deno);\n\n }\n public static int findGCD(int a, int b) {\n while (b != 0) {\n int temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n }\n}\n```
| 1 | 0 |
['Java']
| 0 |
fraction-addition-and-subtraction
|
Greedy || Basic Math || Easiest Solution || Beats 100%
|
greedy-basic-math-easiest-solution-beats-xabf
|
\n# Code\ncpp []\nclass Solution {\npublic:\n string fractionAddition(string expression) {\n vector<pair<int, int>> pt;\n \n int n = exp
|
Kanishq_24je3
|
NORMAL
|
2024-08-23T21:43:11.257990+00:00
|
2024-08-23T21:43:11.258014+00:00
| 14 | false |
\n# Code\n```cpp []\nclass Solution {\npublic:\n string fractionAddition(string expression) {\n vector<pair<int, int>> pt;\n \n int n = expression.size();\n int count = 1;\n int z = 1;\n \n for (int i = 0; i < n; i++) {\n if (expression[i] == \'/\') {\n continue;\n }\n if (expression[i] == \'-\') {\n count = -1;\n continue;\n }\n if (expression[i] == \'+\') {\n count = 1;\n continue;\n }\n int x = 0;\n int zz = 0;\n while (i < n && isdigit(expression[i])) {\n x = x * 10 + (expression[i] - \'0\');\n i++;\n }\n x *= count;\n if (i < n && expression[i] == \'/\') {\n i++;\n while (i < n && isdigit(expression[i])) {\n zz = zz * 10 + (expression[i] - \'0\');\n i++;\n }\n pt.push_back({x, zz});\n z *= zz;\n }\n i--;\n }\n \n int final1 = 0;\n for (auto it : pt) {\n int b = it.second;\n final1 += (it.first * z) / b;\n }\n \n if (final1 == 0) {\n return "0/1";\n }\n \n int gcd_val = gcd(abs(final1), z);\n return to_string(final1 / gcd_val) + "/" + to_string(z / gcd_val);\n }\n\nprivate:\n int gcd(int a, int b) {\n if (b == 0) return a;\n return gcd(b, a % b);\n }\n};\n```
| 1 | 0 |
['Math', 'String', 'Greedy', 'Simulation', 'C++']
| 0 |
fraction-addition-and-subtraction
|
100 % C++ || Easy Implementation
|
100-c-easy-implementation-by-garvit_17-3kdv
|
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
|
garvit_17
|
NORMAL
|
2024-08-23T20:12:42.636165+00:00
|
2024-08-23T20:12:42.636189+00:00
| 6 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string fractionAddition(string expression) {\n int num=0,den=1;\n int i=0,n=expression.size();\n int sign=1;\n if(expression[0]==\'-\'){\n sign=-1;\n i++;\n }\n while(i<n){\n int numerator=0;\n while(i<n and isdigit(expression[i]))\n {\n numerator=10*(numerator)+(expression[i]-\'0\');\n i++;\n }\n numerator*=sign;\n i++;\n int denominator=0;\n while(i<n and isdigit(expression[i]))\n {\n denominator=10*(denominator)+(expression[i]-\'0\');\n i++;\n }\n num=(num*denominator)+(numerator*den);\n den*=denominator;\n int g=gcd(abs(num),den);\n num/=g;\n den/=g;\n sign=1;\n if(expression[i]==\'-\')sign=-1;\n i++;\n }\n return to_string(num) + "/" + to_string(den);\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
fraction-addition-and-subtraction
|
IF YOU HATE URSELF
|
if-you-hate-urself-by-beast820-1vp2
|
Behold the glorious train wreck of code I\'ve concocted. Ever wonder what would happen if string manipulation and math had a baby that went rogue? Well, here it
|
Beast820
|
NORMAL
|
2024-08-23T19:46:28.073644+00:00
|
2024-08-23T19:46:28.073666+00:00
| 9 | false |
Behold the glorious train wreck of code I\'ve concocted. Ever wonder what would happen if string manipulation and math had a baby that went rogue? Well, here it is\u2014a mutant fusion of nonsensical loops, baffling conditionals, and inexplicable logic gaps that defy all reasoning. It\'s like I blindfolded myself and tried to write code with my elbows. Somehow, it still runs... most of the time. Approach with caution; it\u2019s a testament to how far one can stretch the boundaries of acceptable C++ and human decency.\n\n###### **NOTE: The debugging for this code would not be possible without the help of friend, whose name u can find somewhere in this code.**\n\n# Intuition\nNo such intution, i write code on the go.\n\n# Approach\nSimple approach just use if else(not much ~16), for loops,and ton of string indexing to brute force my way through all test cases, so that U dont have to do it.\n\n# Complexity\n- Time complexity:\nEven though it\'s a shitty code, it\'s in O(n).\n\n- Space complexity:\nEven though it\'s a even shittier code, it\'s in O(1).\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int lcm(int a, int b) { return (a * b); }\n\n string fractionAddition(string expression) {\n int len = expression.length();\n string ans;\n int num, dem;\n\n for (int i = 0; i < len - 2; i++) {\n if (i == 0 && expression[i] == \'-\') {\n if (expression[i+1] == \'1\' && expression[i+2] == \'0\') {\n num = -10;\n dem = (expression[i + 4] - \'0\');\n cout << num << endl << dem << endl << endl;\n i = i + 4;\n continue;\n }\n if (expression[i+3] == \'1\' && expression[i+4] == \'0\') {\n num = (expression[i + 1] - \'0\') * (-1);\n dem = 10;\n cout<<"mayank";\n cout << num << endl << dem << endl << endl;\n i = i + 4;\n continue;\n }\n num = (expression[i + 1] - \'0\') * (-1);\n dem = (expression[i + 3] - \'0\');\n cout << num << endl << dem << endl << endl;\n i = i + 3;\n continue;\n } else if (i == 0) {\n if (expression[i] == \'1\' && expression[i+1] == \'0\') {\n num = 10;\n dem = (expression[i + 3] - \'0\');\n cout << num << endl << dem << endl << endl;\n i = i + 3;\n continue;\n }\n if (expression[i+2] == \'1\' && expression[i+3] == \'0\') {\n num = (expression[i] - \'0\');\n dem = 10;\n cout<<"mayank";\n cout << num << endl << dem << endl << endl;\n i = i + 3;\n continue;\n }\n num = (expression[i] - \'0\');\n dem = (expression[i + 2] - \'0\');\n cout << num << endl << dem << endl << endl;\n i = i + 2;\n continue;\n }\n\n if (expression[i] == \'-\') {\n if (expression[i+1] == \'1\' && expression[i+2] == \'0\') {\n num = num * (expression[i + 4] - \'0\') - 10 * dem;\n dem = (expression[i + 4] - \'0\') * dem;\n cout << num << endl << dem << endl << endl;\n i = i + 4;\n continue;\n }\n if (expression[i+3] == \'1\' && expression[i+4] == \'0\') {\n num = (num * 10 - (expression[i + 1] - \'0\') * dem);\n dem = 10 * dem;\n cout<<"mayank";\n cout << num << endl << dem << endl << endl;\n i = i + 4;\n continue;\n }\n num = num * (expression[i + 3] - \'0\') - (expression[i + 1] - \'0\') * dem;\n dem = dem * (expression[i + 3] - \'0\');\n cout << num << endl << dem << endl << endl;\n i = i + 3;\n continue;\n } else {\n if (expression[i+1] == \'1\' && expression[i+2] == \'0\') {\n num = num * (expression[i + 4] - \'0\') + 10 * dem;\n dem = (expression[i + 4] - \'0\') * dem;\n cout << num << endl << dem << endl << endl;\n i = i + 4;\n continue;\n }\n if (expression[i+3] == \'1\' && expression[i+4] == \'0\') {\n num = num * 10 +\n (expression[i + 1] - \'0\') * dem;\n dem = 10 * dem;\n cout << num << endl << dem << endl << endl;\n i = i + 4;\n continue;\n }\n cout << expression[i] << expression[i + 1] << expression[i + 2]\n << expression[i + 3] << endl;\n num = num * (expression[i + 3] - \'0\') +\n (expression[i + 1] - \'0\') * dem;\n dem = lcm(dem, (expression[i + 3] - \'0\'));\n cout << num << endl << dem << endl << endl;\n i = i + 3;\n }\n }\n\n if (abs(num) > abs(dem)) {\n for (int i = abs(dem); i > 1; i--) {\n if (abs(num) % i == 0 && abs(dem) % i == 0) {\n num = num / i;\n dem = dem / i;\n }\n }\n } else {\n for (int i = abs(num); i > 1; i--) {\n if (abs(num) % i == 0 && abs(dem) % i == 0) {\n num = num / i;\n dem = dem / i;\n }\n }\n }\n\n if(num<0 && dem<0){\n num = abs(num);\n dem = abs(dem);\n }\n\n if (num == 0)\n dem = 1;\n\n string nums = to_string(num);\n string dems = to_string(dem);\n\n ans = nums + "/" + dems;\n\n return ans;\n }\n};\n```\n\nThank you for successfully wasting your time, even scrolling through this and reaching here!!
| 1 | 0 |
['C++']
| 1 |
fraction-addition-and-subtraction
|
Java
|
java-by-nishantpri-y9zl
|
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
|
nishantpri
|
NORMAL
|
2024-08-23T19:22:49.956085+00:00
|
2024-08-23T19:22:49.956117+00:00
| 19 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public String fractionAddition(String expression) {\n int nume=0;\n int deno=1;\n char[]ex=expression.toCharArray();\n int i=0;\n while(i<ex.length){\n int currNume=0;\n int currDeno=0;\n boolean isNeg=(ex[i]==\'-\');\n if(ex[i]==\'+\'){\n i++;\n }\n else if(ex[i]==\'-\'){\n isNeg=true;\n i++;\n }\n while(i<ex.length && Character.isDigit(ex[i])){\n int val=ex[i]-\'0\';\n currNume=(currNume*10)+val;\n i++;\n }\n i++;// to skip the devisor char \'/\';\n if(isNeg){\n currNume=-currNume;\n }\n\n while(i<ex.length && Character.isDigit(ex[i])){\n int val=ex[i]-\'0\';\n currDeno=(currDeno*10)+val;\n i++;\n }\n nume=nume*currDeno+currNume*deno;\n deno=deno*currDeno;\n }\n int gcd= Math.abs(findGCD(nume,deno));\n nume/=gcd;\n deno/=gcd;\n return Integer.toString(nume)+"/"+Integer.toString(deno);\n\n }\n public static int findGCD(int a, int b) {\n while (b != 0) {\n int temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n }\n}\n```
| 1 | 0 |
['Java']
| 0 |
fraction-addition-and-subtraction
|
Easy Java Solution
|
easy-java-solution-by-mr_sh_sir-tihy
|
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
|
mr_sh_sir
|
NORMAL
|
2024-08-23T18:47:47.107571+00:00
|
2024-08-23T18:47:47.107608+00:00
| 24 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public String fractionAddition(String expression) {\n ArrayList<Integer>numerator=new ArrayList<>();\n ArrayList<Integer>denominator=new ArrayList<>();\n for(int i=0;i<expression.length();i++){\n char ch=expression.charAt(i);\n int idx=i;\n if(ch==\'/\'){\n int val1=expression.charAt(idx-1)-\'0\';\n if(idx-2>=0){\n if(expression.charAt(idx-2)-\'0\'==1){\n val1=10;\n idx--;\n }\n \n }\n if(idx-2>=0&&expression.charAt(idx-2)==\'-\'){\n val1=-val1;\n }\n idx=i;\n numerator.add(val1);\n int val2=expression.charAt(idx+1)-\'0\';\n if(idx+2<expression.length()){\n if(expression.charAt(idx+2)-\'0\'==0){\n val2=10;\n }\n } \n \n denominator.add(val2);\n }\n }\n System.out.println("numerator="+numerator);\n System.out.println("denominator="+denominator);\n int lcm = denominator.get(0);\n for (int i = 1; i < denominator.size(); i++) {\n lcm = lcm(lcm, denominator.get(i));\n }\n int sum=0;\n for(int i=0;i<denominator.size();i++){\n int fact=lcm/denominator.get(i);\n sum+=numerator.get(i)*fact;\n }\n if(sum==0){\n return sum+"/"+1;\n }\n boolean flag=false;\n if(sum<0){\n flag=true;\n sum=-sum;\n }\n System.out.println("sum="+sum);\n HashMap<Integer,Integer>map1=new HashMap<>();\n HashMap<Integer,Integer>map2=new HashMap<>();\n for (int i = 2; i <= Math.sqrt(sum); i += 1) {\n // While i divides n, add i and divide n\n while (sum % i == 0) {\n map1.put(i, map1.getOrDefault(i, 0) + 1);\n sum /= i;\n }\n }\n if (sum > 1) {\n map1.put(sum, map1.getOrDefault(sum, 0) + 1);\n }\n System.out.println("Before deleting map1="+map1);\n for (int i = 2; i <= Math.sqrt(lcm); i += 1) {\n // While i divides n, add i and divide n\n while (lcm % i == 0) {\n System.out.println("lcm="+lcm);\n if(map1.containsKey(i)&&map1.get(i)>0){\n map1.put(i, map1.get(i)-1);\n }else{\n map2.put(i, map2.getOrDefault(i, 0) + 1);\n }\n lcm/=i;\n System.out.println("end");\n System.out.println("lcm="+lcm);\n System.out.println("i="+i);\n }\n }\n if (lcm > 1) {\n if (map1.containsKey(lcm) && map1.get(lcm) > 0) {\n map1.put(lcm, map1.get(lcm) - 1);\n } else {\n map2.put(lcm, map2.getOrDefault(lcm, 0) + 1);\n }\n }\n int prod1=1,prod2=1;\n System.out.println("map1="+map1);\n System.out.println("map2="+map2);\n for (HashMap.Entry<Integer, Integer> entry : map1.entrySet()) {\n int key = entry.getKey();\n int value = entry.getValue();\n prod1*=(int)Math.pow(key,value);\n }\n for (HashMap.Entry<Integer, Integer> entry : map2.entrySet()) {\n int key = entry.getKey();\n int value = entry.getValue();\n prod2*=(int)Math.pow(key,value);\n }\n if(flag==true){\n prod1=prod1*-1;\n }\n return prod1+"/"+prod2;\n\n }\n public int gcd(int a, int b) {\n if (b == 0) {\n return a;\n }\n return gcd(b, a % b);\n }\n public int lcm(int a, int b) {\n return (a * b) / gcd(a, b);\n }\n}\n```
| 1 | 0 |
['Java']
| 0 |
fraction-addition-and-subtraction
|
🔥✅Beats 100%✅⏲️🔥|| Easy Simple Approach|| C++
|
beats-100-easy-simple-approach-c-by-dege-mqz3
|
\n\n## \uD83D\uDD0D Intuition\n\nGiven a string like "1/3 - 1/2 + 1/4", our goal is to add these fractions and return a single simplified fraction as the result
|
DegeneratorX
|
NORMAL
|
2024-08-23T17:55:03.294516+00:00
|
2024-08-23T17:55:03.294547+00:00
| 28 | false |
\n\n## \uD83D\uDD0D Intuition\n\nGiven a string like `"1/3 - 1/2 + 1/4"`, our goal is to **add** these fractions and return a single simplified fraction as the result. The challenge lies in handling different denominators and maintaining the correct signs for each fraction.\n\n## \uD83D\uDEE0\uFE0F Approach\n\nLet\'s break down the solution step-by-step:\n\n### 1\uFE0F\u20E3 **Initialization**\n- **Variables**:\n - Start with a numerator (`num = 0`) \uD83E\uDDEE and a denominator (`den = 1`).\n - Use a `sign` variable to track whether the current fraction is positive or negative.\n\n### 2\uFE0F\u20E3 **Parsing the String**\n- **Step-by-Step**:\n - Traverse through the string \uD83D\uDCDC, and for each fraction:\n 1. Identify and handle the `+` or `-` signs \u2795\u2796.\n 2. Extract the numerator and denominator of the current fraction.\n\n### 3\uFE0F\u20E3 **Fraction Addition**\n- **Formula**:\n - Update the cumulative numerator and denominator using:\n \\[\n \\text{{new\\_num}} = \\text{{num}} \\times \\text{{currD}} + \\text{{currN}} \\times \\text{{den}}\n \\]\n \\[\n \\text{{new\\_den}} = \\text{{den}} \\times \\text{{currD}}\n \\]\n - This ensures we correctly add fractions by finding a common denominator.\n\n### 4\uFE0F\u20E3 **Simplification**\n- **GCD Calculation**:\n - After processing all fractions, simplify the result by dividing both numerator and denominator by their greatest common divisor (GCD) \uD83D\uDD04.\n - Ensure the correct placement of negative signs if the result is negative.\n\n### 5\uFE0F\u20E3 **Returning the Result**\n- **Final Touch**:\n - If the result is negative, make sure the numerator carries the negative sign \u2796 and return the fraction as a string.\n\n## \u23F2\uFE0F Complexity\n\n- **Time Complexity**: \\(O(n)\\) \u23F1\uFE0F\n - The algorithm processes each character in the string exactly once, so the time complexity is linear with respect to the length of the string.\n \n- **Space Complexity**: \\(O(1)\\) \uD83D\uDCE6\n - The space complexity is constant, as we use a fixed number of variables for calculations.\n\n---\n\n## \uD83E\uDDD1\u200D\uD83D\uDCBB Code Implementation\n```cpp\nclass Solution {\npublic:\n string fractionAddition(string s) {\n int num = 0; // \uD83E\uDDEE Initial numerator\n int den = 1; // \uD83E\uDDEE Initial denominator\n int i = 0; // \uD83D\uDD04 Index for traversing the string\n bool sign = true; // \u2795 Assume positive sign initially\n\n while (i < s.size()) {\n int currN = 0; // Numerator of the current fraction\n int currD = 0; // Denominator of the current fraction\n sign = true; // Reset sign to positive \u2795\n\n char c = s[i];\n\n // \uD83C\uDF10 Handle \'+\' or \'-\' signs\n if (c == \'+\' || c == \'-\') {\n if (c == \'-\') sign = false; // Change sign to negative \u2796\n i++;\n }\n\n // \uD83D\uDCDD Extract the numerator\n int j = i;\n while (i < s.size() && isdigit(s[i])) {\n i++;\n }\n currN = stoi(s.substr(j, i - j)); // Convert to integer\n\n if (!sign) currN = -currN; // Apply sign if needed\n\n i++; // Skip the \'/\' symbol\n\n // \uD83D\uDCDD Extract the denominator\n j = i;\n while (i < s.size() && isdigit(s[i])) {\n i++;\n }\n currD = stoi(s.substr(j, i - j)); // Convert to integer\n\n // \u2795\u2796 Perform the fraction addition\n num = num * currD + currN * den;\n den = den * currD;\n }\n\n // \uD83D\uDD04 Simplify the fraction\n int x = __gcd(num, den);\n num /= x;\n den /= x;\n\n // \u2696\uFE0F Ensure correct sign placement\n if(num < 0 || den < 0) {\n num = abs(num);\n den = abs(den);\n return "-" + to_string(num) + "/" + to_string(den);\n } else {\n return to_string(num) + "/" + to_string(den);\n }\n }\n};\n```\n\n---\n\n
| 1 | 0 |
['C++']
| 2 |
fraction-addition-and-subtraction
|
Easy and explained step-by-step approach 🔥
|
easy-and-explained-step-by-step-approach-kjkg
|
Intuition\nThe problem requires us to add and subtract fractions represented as a string expression. Since fractions can have different denominators, we need to
|
Sonu____
|
NORMAL
|
2024-08-23T17:17:26.317221+00:00
|
2024-08-23T17:17:26.317263+00:00
| 34 | false |
# Intuition\nThe problem requires us to add and subtract fractions represented as a string expression. Since fractions can have different denominators, we need to bring them to a common denominator before performing addition or subtraction. The output should be a simplified fraction.\n# Approach\n- Parse the Input Expression:\n - Traverse through the input string to extract all the fractions and store them in a list (map). Each fraction is represented as a pair of integers (numerator and denominator).\n\n- Calculate the Least Common Multiple (LCM):\n - To perform addition or subtraction, compute the LCM of all denominators to bring all fractions to a common denominator.\n\n- Adjust Numerators and Compute the Resulting Numerator:\n - Adjust the numerators according to the common denominator and sum them up to get the total numerator.\n\n- Simplify the Resulting Fraction:\n - Compute the greatest common divisor (GCD) of the numerator and the denominator to simplify the resulting fraction to its lowest terms.\n\n- Return the Result:\n - Return the simplified fraction in the form of a string.\n\n# Code Explanation\n- fillMap Method: Parses the input string to extract all fractions and store them as integer pairs (numerator, denominator) in the list map.\n\n- LCM and gcd Methods: Helper functions to calculate the least common multiple and greatest common divisor, respectively. These are used to find the common denominator and to simplify the final result.\n\n- fractionAddition Method: Main method that handles the entire process: filling the map with fractions, calculating the LCM, adjusting the numerators, summing them up, and simplifying the result.\n\n# Complexity\n- Time complexity:\n - O(n+k), where n is the size of string and k is the number of fractions in the string.\n- Space complexity:\n O(k), where k is the size of map.\n# Code\n```java []\nclass Solution {\n\n private int gcd(int a, int b){\n while(b != 0){\n int temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n }\n private int LCM(int a, int b){\n return Math.abs(a * (b / gcd(a,b)));\n }\n\n public String fractionAddition(String expression) {\n List<int[]> map = new ArrayList<>();\n fillMap(expression.toCharArray(), map);\n\n int numerator=0, denominator=1;\n\n for (int[] fraction : map) {\n denominator = LCM(denominator, fraction[1]);\n }\n\n for (int[] fraction : map) {\n numerator += fraction[0] * (denominator / fraction[1]);\n }\n\n int gcd = gcd(Math.abs(numerator), denominator);\n numerator /= gcd;\n denominator /= gcd;\n\n return numerator+"/"+denominator;\n\n }\n\n private void fillMap(char[] array, List<int[]> map){\n int N, D, i=0;\n int positive=1, length = array.length;\n\n while(i < length){\n N=0; D=0;\n if(array[i] == \'-\') {\n positive=-1;\n i++;\n } else if(array[i] == \'+\'){\n positive=1;\n i++;\n }\n\n while(i < length && array[i] != \'/\'){\n N = (N * 10) + (int)array[i] - \'0\';\n i++;\n }\n i++;\n while(i < length && array[i] != \'+\' && array[i] != \'-\'){\n D = (D * 10) + (int)array[i] - \'0\';\n i++;\n }\n map.add(new int[] {positive*N, D});\n }\n }\n}\n```
| 1 | 0 |
['Math', 'Java']
| 0 |
fraction-addition-and-subtraction
|
Kotlin. Beats 100% (139 ms). OOP approach + gcd
|
kotlin-beats-100-139-ms-oop-approach-gcd-rl2s
|
\n\n\n# Code\nkotlin []\nclass Solution {\n fun fractionAddition(expression: String): String {\n FractionalNumberReader(expression).use { reader ->\n
|
mobdev778
|
NORMAL
|
2024-08-23T17:06:04.694668+00:00
|
2024-08-23T18:12:08.041332+00:00
| 10 | false |
\n\n\n# Code\n```kotlin []\nclass Solution {\n fun fractionAddition(expression: String): String {\n FractionalNumberReader(expression).use { reader ->\n var number = reader.parseFractionNumber()\n while (reader.ready()) {\n number = number.add(reader.parseFractionNumber())\n }\n return number.toString()\n }\n }\n\n class FractionalNumber(private val m: Int, private val n: Int) {\n\n fun add(other: FractionalNumber): FractionalNumber {\n val newM = m * other.n + other.m * n\n val newN = n * other.n\n val gcd = gcd(newM, newN)\n return FractionalNumber(\n newM / gcd, \n newN / gcd\n )\n }\n\n private fun gcd(a: Int, b: Int): Int {\n var a = a\n var b = b\n while (b != 0) {\n val tmp = a % b\n a = b\n b = tmp\n }\n return a\n }\n\n override fun toString(): String {\n return if (n < 0) "${-m}/${-n}" else "$m/$n"\n }\n }\n\n class FractionalNumberReader(expression: String): AutoCloseable {\n\n val stream = PushbackReader(InputStreamReader(expression.byteInputStream()))\n\n fun ready(): Boolean {\n return stream.ready()\n }\n\n fun parseFractionNumber(): FractionalNumber {\n val m = if (parsePlus()) parseNumber() else -parseNumber()\n parseSeparator()\n val n = parseNumber()\n return FractionalNumber(m, n)\n }\n\n private fun parsePlus(): Boolean = when (val char = stream.read()) {\n \'-\'.code -> false\n \'+\'.code -> true\n else -> { stream.unread(char); true }\n }\n\n private fun parseSeparator() {\n val char = stream.read()\n if (char != \'/\'.code) throw java.lang.IllegalStateException("Unknown separator: ${char.toChar()}")\n }\n\n private fun parseNumber(): Int {\n var number = 0\n while (stream.ready()) {\n val code = stream.read()\n if (code >= \'0\'.code && code <= \'9\'.code) {\n number = number * 10 + (code - \'0\'.code)\n } else {\n stream.unread(code)\n break\n }\n }\n return number\n }\n\n override fun close() {\n stream.close()\n }\n }\n}\n```\n\n# Approach \n\nThe main difficulty of this task is related to the large number of subtasks that arise at different levels.\n\nThe task requires:\n1) Parse each fraction\n2) Add the fractions\n3) Display correctly on the screen\n\n1. Parse each fraction\nFor parsing, I decided to use the standard mechanism - PushbackReader, which allows you to return the last read character. This is very convenient for situations when we expect a number during parsing, but we receive something else from the stream.\n\n2. Add fractions\nThere is nothing complicated here - we apply the standard rule of adding fractions, reducing the upper and lower parts of the fraction by the greatest common divisor. I find the greatest common divisor using the Euclidean algorithm.\n\n3. Display correctly on the screen\nIn the code, I did not bother with the signs that appear in the upper and lower parts of the fraction. But when returning the final result, a correction is necessary if the lower part of the fraction (n) turns out to be negative. If the lower part of the fraction turns out to be negative, simply move the "minus" from the lower part of the fraction to the upper part of the fraction.\n\n# "Growing divisor" approach\n\nAs an alternative, you can consider using a "constantly growing divisor" approach. This is used in some optimizations when you want to avoid unnecessary "heavy" division operations.\n\nWhat is the essence of this approach? It takes a long time to calculate the GCD each time a fraction is added. You can avoid simplifying the fraction after each addition, and do it only at the very end, when a string representation of the fraction is required.\n\nThus, we can simply add fractions to each other without reducing common divisors. This will be a large fraction with an impressive upper and lower parts.\n\nOnly when we reach the operation of obtaining the final result - only then will the GCD algorithm be called and the reduction will be performed.\n\n\n\n```\nclass Solution {\n fun fractionAddition(expression: String): String {\n FractionalNumberReader(expression).use { reader ->\n var number = reader.parseFractionNumber()\n while (reader.ready()) {\n number = number.add(reader.parseFractionNumber())\n }\n return number.toString()\n }\n }\n\n class FractionalNumber(private val m: BigInteger, private val n: BigInteger) {\n\n fun add(other: FractionalNumber): FractionalNumber {\n return FractionalNumber(m * other.n + other.m * n, n * other.n)\n }\n\n override fun toString(): String {\n val gcd = m.gcd(n)\n var newM = m / gcd\n var newN = n / gcd\n if (newN.signum() < 0) { newM = -newM; newN = -newN }\n return "$newM/$newN"\n }\n }\n\n class FractionalNumberReader(expression: String): AutoCloseable {\n\n val stream = PushbackReader(InputStreamReader(expression.byteInputStream()))\n\n fun ready(): Boolean {\n return stream.ready()\n }\n\n fun parseFractionNumber(): FractionalNumber {\n val plus = parsePlus()\n val m = parseNumber()\n parseSeparator()\n val n = parseNumber()\n return FractionalNumber(\n BigInteger(if (plus) 1 else -1, byteArrayOf(m.toByte())),\n BigInteger(1, byteArrayOf(n.toByte()))\n )\n }\n\n private fun parsePlus(): Boolean = when (val char = stream.read()) {\n \'-\'.code -> false\n \'+\'.code -> true\n else -> { stream.unread(char); true }\n }\n\n private fun parseSeparator() {\n val char = stream.read()\n if (char != \'/\'.code) throw java.lang.IllegalStateException("Unknown separator: ${char.toChar()}")\n }\n\n private fun parseNumber(): Int {\n var number = 0\n while (stream.ready()) {\n val code = stream.read()\n if (code >= \'0\'.code && code <= \'9\'.code) {\n number = number * 10 + (code - \'0\'.code)\n } else {\n stream.unread(code)\n break\n }\n }\n return number\n }\n\n override fun close() {\n stream.close()\n }\n }\n}\n```
| 1 | 0 |
['Kotlin']
| 0 |
fraction-addition-and-subtraction
|
Efficient way to solve the problem using Regex pattern match
|
efficient-way-to-solve-the-problem-using-x5cf
|
Intuition\nTo solve fraction addition and subtraction, convert all fractions to a common denominator, sum their numerators, and reduce the result to its simples
|
Volcandrabuzz
|
NORMAL
|
2024-08-23T17:00:37.859626+00:00
|
2024-08-23T17:00:37.859665+00:00
| 38 | false |
# Intuition\nTo solve fraction addition and subtraction, convert all fractions to a common denominator, sum their numerators, and reduce the result to its simplest form. If the result is an integer, express it as a fraction with denominator 1 (e.g., 2/1). This ensures the arithmetic is accurate and the output is in its most simplified form.\n\n# Approach\n# 1. **Parse the Expression:**\n- **Identify Fractions:** Split the string into individual fractions and signs using a regular expression. This ensures we correctly handle both positive and negative fractions. You can use a regex pattern like (?=[+-]) to separate the fractions based on the signs.\n- **Handle Mixed Signs:** Ensure that the parsing captures both positive and negative signs for each fraction.\n# 2. Normalize Fractions:\n- **Common Denominator:** To add or subtract fractions, they need to have the same denominator. The least common denominator (LCD) of the fractions can be used for this purpose.\n- **Convert Each Fraction:** Convert each fraction to have this common denominator, adjusting the numerators accordingly.\n# 3. Perform Addition/Subtraction:\n- **Sum the Numerators:** After normalizing the fractions, add or subtract the numerators based on the sign. The denominator remains the common denominator.\n- **Simplify the Result:** The final fraction may need to be reduced to its irreducible form by dividing both the numerator and denominator by their greatest common divisor (GCD).\n# 4. Format the Result:\n- **Check for Integer Result:** If the numerator is divisible by the denominator, return the result as an integer over 1 (e.g., 2/1).\nOtherwise: Return the fraction in its reduced form.\n# Complexity\n- Time complexity:O(N)\n\n- Space complexity:O(N)\n\n# Code\n```java []\nclass Solution {\n public int gcd(int a, int b) {\n return b == 0 ? a : gcd(b, a % b);\n }\n public int lcm(int a, int b) {\n return (a / gcd(a, b)) * b;\n }\n\n public String fractionAddition(String expression) {\n String[] sep = expression.split("(?=[+-])|/");\n if (sep.length == 2) return expression;\n\n int[] parts = new int[sep.length];\n for (int i = 0; i < sep.length; i++) {\n parts[i] = Integer.parseInt(sep[i]);\n }\n int lcm = parts[1];\n for (int i = 3; i < parts.length; i += 2) {\n lcm = lcm(lcm, parts[i]);\n }\n int sum = 0;\n for (int i = 1; i < parts.length; i += 2) {\n sum += parts[i - 1] * (lcm / parts[i]);\n }\n int gcd = gcd(Math.abs(sum), lcm);\n return (sum / gcd) + "/" + (lcm / gcd);\n }\n}\n\n```
| 1 | 0 |
['Java']
| 1 |
fraction-addition-and-subtraction
|
"Efficient Fraction Addition and Simplification in Java"
|
efficient-fraction-addition-and-simplifi-9h5c
|
Intuition\nThis code performs fraction addition and subtraction by processing a string expression of fractions. It first splits the expression into individual f
|
IMAM_KHANN
|
NORMAL
|
2024-08-23T16:43:15.131231+00:00
|
2024-08-23T16:43:15.131273+00:00
| 22 | false |
# Intuition\nThis code performs fraction addition and subtraction by processing a string expression of fractions. It first splits the expression into individual fractions using the signs (+ and -) as delimiters. The initial numerator num is set to 0, and the denominator den is set to 1. It then iterates through each fraction, parsing the numerator and denominator, and accumulates the result by converting each fraction to a common denominator and adding it to the cumulative sum. After processing all fractions, it checks if the numerator is zero; if so, it returns "0/1". Otherwise, it simplifies the fraction by dividing both the numerator and denominator by their greatest common divisor (GCD). Finally, it returns the simplified fraction in the form of a string "numerator/denominator". The gcd method is a helper function that computes the greatest common divisor using a subtraction-based approach.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```java []\nclass Solution {\n public String fractionAddition(String expression) {\n // Split the input string into individual fractions based on the \'+\' or \'-\' signs\n String frs[] = expression.split("(?=[+-])");\n \n // Initialize the numerator as 0 and the denominator as 1\n long num = 0, den = 1;\n\n // Iterate over each fraction string\n for (String fr : frs) {\n // Split the fraction string into numerator and denominator\n String[] curr = fr.split("/");\n long a = Long.parseLong(curr[0]); // Parse the numerator\n long b = Long.parseLong(curr[1]); // Parse the denominator\n \n // Update the cumulative numerator and denominator\n num = num * b + a * den;\n den = den * b;\n }\n\n // If the numerator is zero, return "0/1"\n if (num == 0) return "0/1";\n \n // Calculate the greatest common divisor (GCD) of the numerator and denominator\n long gcd = gcd(Math.abs(num), Math.abs(den));\n \n // Simplify the fraction by dividing both numerator and denominator by their GCD\n num /= gcd;\n den /= gcd;\n \n // Return the simplified fraction as a string\n return num + "/" + den;\n }\n\n // Helper method to compute the greatest common divisor (GCD) using subtraction\n private long gcd(long a, long b) {\n if (a == b) return a;\n if (a > b) return gcd(a - b, b);\n return gcd(a, b - a);\n }\n}\n\n```
| 1 | 0 |
['Java']
| 0 |
fraction-addition-and-subtraction
|
Easy solution in C++
|
easy-solution-in-c-by-mahajanmayur06-l1ic
|
Intuition\n Describe your first thoughts on how to solve this problem. \nString is valid, So when \'/\' is encountered we will have to get the numerator (left s
|
mahmayur06
|
NORMAL
|
2024-08-23T16:40:14.451080+00:00
|
2024-08-23T16:40:14.451114+00:00
| 21 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nString is valid, So when \'/\' is encountered we will have to get the numerator (left side) and denominator(right side) to calculate the fraction, if sign is encounter set the sign as positive or negative to push numerator of correct sign.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Parsing the Expression:\n- The input string expression contains fractions separated by either + or - signs.\n- Each fraction has a numerator and a denominator, separated by a / symbol.\n- The goal is to extract these fractions and their corresponding signs, then compute the sum or difference of these fractions.\n\n2. Handling Multiple Digits:\n- Since the numerators and denominators can have multiple digits, carefully parse the entire number before and after the /.\n- Use the existing logic to handle positive and negative signs.\n\n3. Common Denominator Calculation:\n- To add or subtract fractions, they must be converted to have a common denominator.\n- The least common multiple (LCM) of the denominators is used to find this common denominator.\n\n4. Summing the Fractions:\n- Convert each fraction to the common denominator and sum their numerators.\n- Handle the sign of the fraction based on the parsed sign (+ or -).\n\n5. Simplifying the Result:\n- After summing the fractions, the result should be simplified by dividing both the numerator and the denominator by their greatest common divisor (GCD).\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> \n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string fractionAddition(string expression) {\n vector<pair<int, int>> fraction;\n int n = expression.size();\n bool isPos = true;\n int val = 1;\n for (int i = 0; i < n; i++) {\n if (expression[i] == \'+\') {\n isPos = true;\n }\n else if (expression[i] == \'-\') {\n isPos = false;\n }\n if (expression[i] == \'/\') {\n int num = expression[i - 1] - \'0\', den = expression[i + 1] - \'0\';\n if (i > 1 && expression[i - 2] >= \'0\' && expression[i - 2] <= \'9\') {\n num = num + (expression[i - 2] - \'0\') * 10;\n }\n if (i < n - 1 && expression[i + 2] >= \'0\' && expression[i + 2] <= \'9\') {\n den = den * 10 + (expression[i + 2] - \'0\');\n }\n val = lcm(den, val);\n if (!isPos) {\n fraction.push_back({-num, den});\n }\n else \n fraction.push_back({num, den});\n }\n }\n n = fraction.size();\n int num = 0, den = val;\n for (int i = 0 ; i < n; i++) {\n int temp = fraction[i].first * val / fraction[i].second;\n num += temp;\n }\n if (num == 0) return "0/1";\n return to_string(num / gcd(num, den)) + "/" + to_string(den / gcd(num, den));\n }\n};\n```
| 1 | 0 |
['Math', 'C++']
| 0 |
minimum-amount-of-time-to-fill-cups
|
[Java/C++/Python] max(max(A), (sum(A) + 1) / 2)
|
javacpython-maxmaxa-suma-1-2-by-lee215-z6sa
|
Explanation\nIt\'s a brain-teaser.\n\nNecessary conditions (lower bound)\n1. res >= max(A)\nBecause each time,\none type can reduce at most 1 cup,\nso the final
|
lee215
|
NORMAL
|
2022-07-10T04:05:29.850619+00:00
|
2022-07-14T09:15:32.555415+00:00
| 12,698 | false |
# **Explanation**\nIt\'s a brain-teaser.\n\n**Necessary conditions (lower bound)**\n1. `res >= max(A)`\nBecause each time,\none type can reduce at most 1 cup,\nso the final result is bigger or equal to `max(A)`\n\n2. `res >= ceil(sum(A) / 2)`\nBecause each time,\nwe can fill up to 2 cups,\nso the final result is bigger or equal to `ceil(sum(A) / 2)`\n\n**Sufficient considtion (realizeable)**\nOne strategy is to greedily fill up 2 cups with different types of water.\nEach step, we pick the 2 types with the most number of cups, until there is only one kind.\n\n**Conclusion**\nThe lower bound is realizable,\nso it\'s proved as the minimum steps.\n<br>\n\n# **Complexity**\nTime `O(n)`\nSpace `O(1)`\n<br>\n\n**Java**\n```java\n public int fillCups(int[] A) {\n int mx = 0, sum = 0;\n for(int a: A) {\n mx = Math.max(a, mx);\n sum += a;\n }\n return Math.max(mx, (sum + 1) / 2);\n }\n```\n\n**C++**\n```cpp\n int fillCups(vector<int>& A) {\n int mx = 0, sum = 0;\n for(int& a: A) {\n mx = max(a, mx);\n sum += a;\n }\n return max(mx, (sum + 1) / 2);\n }\n```\n\n**Python**\n```py\n def fillCups(self, A):\n return max(max(A), (sum(A) + 1) // 2)\n```\n
| 209 | 4 |
['C', 'Python', 'Java']
| 29 |
minimum-amount-of-time-to-fill-cups
|
I did not work out the 1st problem, first time!!
|
i-did-not-work-out-the-1st-problem-first-yuc3
|
I did not work out the 1st problem, first time!! So Stupid!\n\nUpdate: 1 min after this end, I came up with this lol:\n\nExplanation: We can only care about the
|
leetcodefunker
|
NORMAL
|
2022-07-10T04:00:42.193229+00:00
|
2022-07-10T04:15:57.574738+00:00
| 4,532 | false |
I did not work out the 1st problem, first time!! So Stupid!\n\n**Update:** **1 min after this end, I came up with this lol:**\n\nExplanation: We can only care about the largest 2 elements in the array and try to fill them at one time, then dynamically find the largest 2 elements in the next loops, do the same thing until we fill all the cups. \n\n```\n public int fillCups(int[] amount) {\n Arrays.sort(amount);\n int res = 0;\n while (amount[2] != 0) {\n res++;\n amount[2]--;\n if (amount[1] > 0) {\n amount[1]--;\n }\n Arrays.sort(amount);\n }\n return res;\n }\n```\n\n**Thanks your guys\' upvotes for making me less unhappy!**
| 69 | 0 |
[]
| 20 |
minimum-amount-of-time-to-fill-cups
|
Java Solution- Easy To Understand
|
java-solution-easy-to-understand-by-abhi-tj65
|
\nclass Solution {\n public int fillCups(int[] amount) {\n int seconds = 0;\n Arrays.sort(amount);//First sorting the array.\n int highe
|
Abhinav_0561
|
NORMAL
|
2022-07-10T04:00:26.720593+00:00
|
2022-07-10T04:53:52.289209+00:00
| 4,601 | false |
```\nclass Solution {\n public int fillCups(int[] amount) {\n int seconds = 0;\n Arrays.sort(amount);//First sorting the array.\n int highestNum = amount.length-1;\n int secondHighestNum = amount.length-2;\n //Now taking the two biggest numbers of the array which will be at the last and the second last index as the array is sorted.\n while (amount[highestNum]>0 && amount[secondHighestNum]>0){\n //If both these numbers are greater than 0 then we can fill two cups in one second and then decreasing their values.\n amount[highestNum]--;\n amount[secondHighestNum]--;\n seconds++;//This is one ans\n Arrays.sort(amount);//Now, again sorting using the inbuilt sort of java class so that the biggest two numbers are at the last two index of the array\n }\n\n //The above loop will break when either of the two places becomes 0\n //If the number at last and secon last index were equal, then both of them will become zero\n //Or if it is not the case, then only one type of water is present in the dispenser\n while (amount[highestNum]>0){\n //So, decreasing it one by one till it becomes zero\n amount[highestNum]--;\n seconds++;\n }\n return seconds;//Hence, we have found our answer\n }\n}\n```\nComment if there is any doubt.\nIf you liked the solution or found it easy to understand, do upvote :)\nThankyou!!
| 36 | 0 |
['Array', 'Sorting', 'Java']
| 11 |
minimum-amount-of-time-to-fill-cups
|
c++ | easy
|
c-easy-by-nitin23rathod-3uo4
|
\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n sort(amount.begin(),amount.end()); \n int x=amount[0];\n int y=amount[1];\
|
nitin23rathod
|
NORMAL
|
2022-07-10T04:01:07.643379+00:00
|
2022-07-10T10:23:42.629599+00:00
| 3,499 | false |
```\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n sort(amount.begin(),amount.end()); \n int x=amount[0];\n int y=amount[1];\n int z=amount[2];\n int sum=x+y+z;\n if(x+y>z) return sum/2+sum%2;\n if(x==0 && y==0) return z;\n else return z;\n }\n};\n```\n**Upvote if you like my approch**\n\n\n
| 27 | 0 |
['C']
| 7 |
minimum-amount-of-time-to-fill-cups
|
Rigorous proof of the correct strategy and the O(1) formula solution
|
rigorous-proof-of-the-correct-strategy-a-3bxq
|
After reading several posts in this discussion, I wasn\'t able\xA0to find a formal rigorous\xA0proof of why the O(n) sorting (or priority queue) method works or
|
s7amail
|
NORMAL
|
2022-07-17T08:08:44.866086+00:00
|
2022-07-17T08:09:10.507641+00:00
| 1,047 | false |
After reading several posts in this discussion, I wasn\'t able\xA0to find a formal rigorous\xA0proof of why the O(n) sorting (or priority queue) method works or why the O(1) formula\xA0method is correct. So, after some thought, here is a proof.\nI don\'t think it should\xA0be considered an "easy" problem even though the actual solution is simple.\n\n### Problem statement\n\nI use a slightly\xA0different formulation of the problem since it is more convenient.\nWe have 3 columns of non-negative integer\xA0height. Our goal is to reach a state where all of them are zero with two types of operations:\n1. Decrement 1 from one of the columns.\n2. Decrement 1 from two\xA0different\xA0columns.\n\nThe task is to calculate the minimum number of steps necessary.\n\n### Lower bound\nAs others already mentioned, there are two obvious\xA0lower bounds:\n1. max(columns): since at each step a maximum\xA0of 1 is decremented from a single column.\n2. ceil(sum(columns) / 2): since at each step a maximum of 2 is decremented from the sum of the\xA0columns.\n\nSo the lower bound is the maximum of the two numbers above.\n\n### Proof the lower bound is also reachable\nLet\'s denote the column values a >= b >= c >= 0.\n\n(1) If a >= b+c, then we use c steps to remove c from the first and last columns and reach a-c, b, 0. Then, we use b steps to remove b from the first and second to reach a-b-c, 0 ,0. Then, we remove the remaining with a-b-c steps. We used a total of exactly c\xA0+ b\xA0+ a - b - c = a = max(columns) steps, thus achieving our lower bound.\n\n(2) Now suppose that, a < b+c.\nLet x = a-b >= 0 and y=b-c >= 0. Therefore, we have: a=x+y+c, b=y+c. At first, we use y operations (from the second type) to decrement y from the two largest columns. After that we have the values x+c, c, c where x < c.\n\n(2.1) If x+c is even:\nThere exists k>0 such that x+c=2k. Note that k < c since x < c. We use k steps to remove k from the first and second columns to reach k, c-k, c. Now again use k steps to remove k from the first and third columns to reach 0, c-k, c-k. Finally, use c-k steps to zeroize the two equal remaining columns. All the steps we used were from the second type, i.e. remove 2 each time so the total number of steps was exactly sum(columns) / 2 and we again reached the lower bound.\n\n(2.2) If x+c is odd:\nThere exists k>0 such that x+c=2k+1. Note that k < c since x < c. We use k steps to remove k from the first and second columns to reach k+1, c-k, c. Now again use k steps to remove k from the first and third columns to reach 1, c-k, c-k. Finally, use c-k steps to zeroize the two equal columns and one more step of the first type to zeroize the first column. All the steps except the last one were from the second type so the total number of steps was exactly\xA0ceil(sum(columns) / 2)\xA0and we again reached the lower bound.\n\nQ.E.D\n\nPlease note the above also proves the correctness of the sorting (or priority queue) strategy.
| 25 | 0 |
['Math']
| 0 |
minimum-amount-of-time-to-fill-cups
|
Simulation and Formula
|
simulation-and-formula-by-votrubac-pk0w
|
Simulation\nWe pick two largest piles, and fill two cups (or one, if we have only one pile left).\n\nC++\ncpp\nint fillCups(vector<int>& a) {\n int res = 0;\
|
votrubac
|
NORMAL
|
2022-07-10T21:28:39.966542+00:00
|
2022-10-05T16:48:47.189656+00:00
| 2,006 | false |
#### Simulation\nWe pick two largest piles, and fill two cups (or one, if we have only one pile left).\n\n**C++**\n```cpp\nint fillCups(vector<int>& a) {\n int res = 0;\n for (; max({a[0], a[1], a[2]}) > 0; ++res) {\n sort(begin(a), end(a));\n --a[2];\n --a[1];\n }\n return res;\n}\n```\n#### Formula\nIf we have one pile much larger than the others, the number of seconds will be the same as the number of cups in that large pile.\n\nOr, if piles are of similar size, and we can always fill two cups, we will need `(a[0] + a[1] + a[2] + 1) / 2` seconds (we do `+ 1` in case the sum of cups is odd).\n\n**C++**\n```cpp\nint fillCups(vector<int>& a) {\n return max({a[0], a[1], a[2], (a[0] + a[1] + a[2] + 1) / 2});\n}\n```
| 24 | 1 |
['C']
| 4 |
minimum-amount-of-time-to-fill-cups
|
[ Go , Python , C++ , Java, Javascript ] sorting and filling up 2 biggest at same time w/ comments
|
go-python-c-java-javascript-sorting-and-gfnzu
| null |
carti
|
NORMAL
|
2022-07-11T03:04:35.169406+00:00
|
2022-07-11T03:36:31.847969+00:00
| 1,350 | false |
<iframe src="https://leetcode.com/playground/BZ3Fa793/shared" frameBorder="0" width="900" height="600"></iframe>
| 13 | 0 |
['C', 'Python', 'C++', 'Java', 'Go', 'Python3', 'JavaScript']
| 2 |
minimum-amount-of-time-to-fill-cups
|
Priority Queue ease solu C++
|
priority-queue-ease-solu-c-by-stud_64-4rl9
|
class Solution {\npublic:\n int fillCups(vector& amount) {\n priority_queue q;\n \n // fill qunatity of cups\n for(int i=0; i0)q.
|
stud_64
|
NORMAL
|
2022-07-10T04:01:05.258837+00:00
|
2022-07-10T04:01:05.258879+00:00
| 1,713 | false |
class Solution {\npublic:\n int fillCups(vector<int>& amount) {\n priority_queue<int> q;\n \n // fill qunatity of cups\n for(int i=0; i<amount.size(); i++){\n if(amount[i]>0)q.push(amount[i]);\n }\n \n int day = 0;\n while(!q.empty() && q.size()>1){\n // check first two elements decrease them and again push to priority queue\n int a = q.top() - 1;\n q.pop();\n \n int b = q.top() - 1;\n q.pop();\n \n day++;\n if(a>0) q.push(a);\n if(b>0) q.push(b);\n }\n \n // check if any element is left\n if(q.size()) day+=q.top();\n \n return day;\n\n }\n};
| 13 | 0 |
['Heap (Priority Queue)']
| 2 |
minimum-amount-of-time-to-fill-cups
|
🙏 C++,Basic Math, 100% beats both time and space complexity
|
cbasic-math-100-beats-both-time-and-spac-7wuh
|
Hi EveryOne , In this I am going to solve this question using basic mathematics.\nTime Complexity O(n) and Space Complexity O(1)\n\nEquation 1-> Each second we
|
vikramsinghgurjar
|
NORMAL
|
2022-07-10T15:46:56.157609+00:00
|
2022-07-10T17:17:14.967998+00:00
| 438 | false |
Hi EveryOne , In this I am going to solve this question using basic mathematics.\n**Time Complexity O(n) and Space Complexity O(1)**\n\n**Equation 1->** ```Each second we fill (either different or same cup) we cannot reduce the amount of cups(of one type) to be filled by more than 1 so we need atleast max(amount) seconds to fill all solution. Got it ? So sol>=max(amount)```\n**Equation 2 ->** ```what will be minimum second required if we fill 2 cups each second then we will need ceil((total amount to fill)/2) So Solution would be Sol>=((total+1)/2)```\n\t\n\tOverall solution should satisfy both equations.\n\n```\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n int maxi=0;\n int total =0;\n for(int i=0;i<amount.size();i++){\n total+=amount[i];\n maxi=max(maxi,amount[i]);\n }\n // It is based on basic Math\n /** Case I EQUATION I- Each second we fill (either different or same cup) \n\t\twe cannot reduce the amount of maximum cups to be filled by more than 1\n\t\tso we need atleast max(amount) seconds to \n\t\tfill all solution. Got it ? \n\t\tSo sol>=max(amount)\n\t\t\n Equation 2 -> what will be minimum second required \n\t\tif we fill 2 cups each second then we will need ceil((total amount to fill)/2) \n\t\tSo Solution would be Sol>=((total+1)/2)\n **/\n // Overall solution should satisfy both equations.\n return max(maxi,(total+1)/2);\n }\n};\n```\n\n**Please Upvote if you like it and if you have any query. comment section is all yours \uD83D\uDE4F**\n\n\n
| 10 | 0 |
['Math', 'C++']
| 1 |
minimum-amount-of-time-to-fill-cups
|
Python | Straightforward MaxHeap Solution
|
python-straightforward-maxheap-solution-jyqfy
|
\nclass Solution:\n def fillCups(self, amount: List[int]) -> int:\n pq = [-q for q in amount if q != 0]\n heapq.heapify(pq)\n ret = 0\n
|
lukefall425
|
NORMAL
|
2022-07-10T05:58:50.951372+00:00
|
2022-07-10T05:58:50.951439+00:00
| 2,196 | false |
```\nclass Solution:\n def fillCups(self, amount: List[int]) -> int:\n pq = [-q for q in amount if q != 0]\n heapq.heapify(pq)\n ret = 0\n \n while len(pq) > 1:\n first = heapq.heappop(pq)\n second = heapq.heappop(pq)\n first += 1\n second += 1\n ret += 1\n if first:\n heapq.heappush(pq, first)\n if second:\n heapq.heappush(pq, second)\n\n if pq:\n return ret - pq[0]\n else:\n return ret\n```
| 10 | 0 |
['Heap (Priority Queue)', 'Python', 'Python3']
| 2 |
minimum-amount-of-time-to-fill-cups
|
Python3 || one line w/explanation || T/S: 90% / 82%
|
python3-one-line-wexplanation-ts-90-82-b-524x
|
Here\'s the intuition:\n\nBecause only one of any type can be filled per second, the minimum cannot be less than the max(amount)-- see Ex 1.\n\n The minimum als
|
Spaulding_
|
NORMAL
|
2022-07-10T23:04:58.465624+00:00
|
2024-06-13T07:08:57.004475+00:00
| 666 | false |
Here\'s the intuition:\n\nBecause only one of any type can be filled per second, the minimum cannot be less than the max(amount)-- see Ex 1.\n\n The minimum also cannot be less than `ceil(sum(amount)/2)`--see Ex 2.\n \n The mminimumin cannot be greater than both of these two\n quantities, so... tada\n```\nclass Solution:\n def fillCups(self, amount: List[int]) -> int:\n return max(max(amount), ceil(sum(amount)/2))\n```\n[https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/submissions/1286771753/](https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/submissions/1286771753/)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(1), in which *N* ~ `len(amount)`.
| 9 | 0 |
['Python3']
| 0 |
minimum-amount-of-time-to-fill-cups
|
[Python] Sorting Based
|
python-sorting-based-by-tejeshreddy111-xdpf
|
Approach\n- Continously sort and decrement the first and second value by 1 till the first value is 0. Later return the count\n\nCode\n\nclass Solution:\n def
|
tejeshreddy111
|
NORMAL
|
2022-07-10T04:16:42.794341+00:00
|
2022-07-10T04:33:42.862722+00:00
| 491 | false |
Approach\n- Continously sort and decrement the first and second value by 1 till the first value is 0. Later return the count\n\nCode\n```\nclass Solution:\n def fillCups(self, amount: List[int]) -> int:\n \n count = 0\n amount = sorted(amount, reverse=True)\n while amount[0] > 0:\n amount[0] -= 1\n amount[1] -= 1\n count += 1\n amount = sorted(amount, reverse=True)\n return count\n```\n\n
| 9 | 0 |
['Python']
| 0 |
minimum-amount-of-time-to-fill-cups
|
Java Easiest Solution
|
java-easiest-solution-by-subhabratamajee-nv02
|
Please Upvote\n\nclass Solution {\n public int fillCups(int[] amount) {\n Arrays.sort(amount);\n int x=amount[0];\n int y=amount[1];\n
|
Subhabratamajee
|
NORMAL
|
2022-07-10T04:04:18.318263+00:00
|
2022-07-10T04:04:18.318308+00:00
| 1,356 | false |
# Please Upvote\n```\nclass Solution {\n public int fillCups(int[] amount) {\n Arrays.sort(amount);\n int x=amount[0];\n int y=amount[1];\n int z=amount[2];\n int sum=x+y+z;\n if(x+y>z){return sum/2 +sum%2;}\n if(x==0&&y==0){return z;}\n else{return z;}\n }\n}\n```
| 9 | 0 |
['Sorting', 'Java']
| 4 |
minimum-amount-of-time-to-fill-cups
|
Easy Recursion | | C++
|
easy-recursion-c-by-harsh_negi_07-g5ee
|
We have two type of moves \n\t1. fill 2 different cups \n\t2. fill 1 cup\nObservation .. \n\talways decrement from 2 maximum cups\n\twhen 2 cups become ZERO, em
|
negiharsh12
|
NORMAL
|
2022-07-10T04:01:54.157550+00:00
|
2022-07-10T04:11:35.161570+00:00
| 1,248 | false |
We have two type of moves \n\t1. fill 2 different cups \n\t2. fill 1 cup\nObservation .. \n\talways decrement from 2 maximum cups\n\twhen 2 cups become ZERO, empty the last cup in single move\n\n```\nclass Solution { \nprivate:\n // counter for Steps\n int count = 0;\n void check(vector<int>& a){\n // sort the array \n sort(a.begin(), a.end());\n // base case // if all elements are ZERO\n if (a[0] + a[1] + a[2] == 0) return;\n // decrement from last to element\n if (a[1] and a[2]){\n a[1]--, a[2]--;\n count++;\n }\n else{\n // at this point only last element is non zero // so we can directly make it zero\n count += a[2];\n a[2] = 0;\n }\n // recursive call \n check(a);\n }\npublic:\n int fillCups(vector<int>& a) {\n check(a);\n return count;\n }\n};\n```\n
| 9 | 1 |
['C']
| 2 |
minimum-amount-of-time-to-fill-cups
|
C++ solutions
|
c-solutions-by-infox_92-jma8
|
class Solution {\npublic:\n int fillCups(vector& amount) {\n sort(amount.begin(),amount.end()); \n int x=amount[0];\n int y=amount[1];\n
|
Infox_92
|
NORMAL
|
2022-11-20T06:39:21.938939+00:00
|
2022-11-20T06:39:21.938981+00:00
| 1,582 | false |
class Solution {\npublic:\n int fillCups(vector<int>& amount) {\n sort(amount.begin(),amount.end()); \n int x=amount[0];\n int y=amount[1];\n int z=amount[2];\n int sum=x+y+z;\n if(x+y>z) return sum/2+sum%2;\n if(x==0 && y==0) return z;\n else return z;\n }\n};
| 7 | 0 |
['Dynamic Programming', 'C', 'C++']
| 3 |
minimum-amount-of-time-to-fill-cups
|
C++ Easy & Simple Solution || O(1)
|
c-easy-simple-solution-o1-by-anayet-5d0z
|
\nclass Solution {\npublic:\n int fillCups(vector<int>& a) {\n int sum = a[0]+a[1]+a[2];\n int maxValue = max(a[0], max(a[1], a[2]));\n
|
anayet
|
NORMAL
|
2022-07-15T15:44:19.053222+00:00
|
2023-07-14T09:18:14.062470+00:00
| 816 | false |
```\nclass Solution {\npublic:\n int fillCups(vector<int>& a) {\n int sum = a[0]+a[1]+a[2];\n int maxValue = max(a[0], max(a[1], a[2]));\n return max(maxValue, (sum+1)/2);\n }\n};\n```\n**Time Complexity = O(1)\nSpace Complexity = O(1)**
| 7 | 0 |
['C++']
| 2 |
minimum-amount-of-time-to-fill-cups
|
C++ | One line solution
|
c-one-line-solution-by-rajat7k-rd4m
|
\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n return max(*max_element(begin(amount),end(amount)),(accumulate(begin(amount),end(a
|
rajat7k
|
NORMAL
|
2022-07-11T05:20:53.643444+00:00
|
2022-07-11T05:20:53.643489+00:00
| 460 | false |
```\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n return max(*max_element(begin(amount),end(amount)),(accumulate(begin(amount),end(amount),0)+1)/2);\n }\n};\n```
| 6 | 0 |
['C++']
| 0 |
minimum-amount-of-time-to-fill-cups
|
Minimum Amount of Time to Fill Cups | Java Solution
|
minimum-amount-of-time-to-fill-cups-java-5qb2
|
\nclass Solution {\n public int fillCups(int[] amount) {\n Arrays.sort(amount);\n int high = amount[2];\n int mid = amount[1];\n
|
shaguftashahroz09
|
NORMAL
|
2022-07-10T04:00:43.444436+00:00
|
2022-07-10T04:00:43.444463+00:00
| 657 | false |
```\nclass Solution {\n public int fillCups(int[] amount) {\n Arrays.sort(amount);\n int high = amount[2];\n int mid = amount[1];\n int low = amount[0];\n int tot=high+mid+low; \n if(low+mid>high) \n return tot/2+tot%2; \n if(low==0 && mid==0) \n return high; \n else \n return high; \n\n }\n }\n\n```
| 6 | 0 |
['Java']
| 0 |
minimum-amount-of-time-to-fill-cups
|
✅🔥Just Priority Heap✅🔥
|
just-priority-heap-by-manohar_001-a7hc
|
\uD83D\uDE09Don\'t just watch & move away, also give an Upvote.\uD83D\uDE09\n\n# Complexity\n- Time complexity: O(n.log(n))\n Add your time complexity here, e.g
|
Manohar_001
|
NORMAL
|
2023-06-21T19:17:06.140191+00:00
|
2023-06-21T19:17:06.140217+00:00
| 427 | false |
# \uD83D\uDE09Don\'t just watch & move away, also give an Upvote.\uD83D\uDE09\n\n# Complexity\n- Time complexity: $$O(n.log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n priority_queue<int> pq;\n\n pq.push(amount[0]);\n pq.push(amount[1]);\n pq.push(amount[2]);\n\n\n int time = 0,first = 0, second = 0;\n while(pq.top() != 0)\n {\n time++;\n\n if(pq.top() != 0){\n first = pq.top();\n pq.pop();\n first--;\n }\n\n if(pq.top() != 0){\n second = pq.top();\n pq.pop();\n second--;\n }\n\n pq.push(first);\n pq.push(second);\n \n }\n\n\n<!-- \u2705Well before returning answer don\'t forget to UPVOTE.\u2705 -->\n return time;\n }\n};\n```\n
| 5 | 0 |
['C', 'Heap (Priority Queue)', 'C++', 'Java']
| 1 |
minimum-amount-of-time-to-fill-cups
|
[C++] 2 Method { (maximum of max and sum ) + (Sorting decreasing order) }
|
c-2-method-maximum-of-max-and-sum-sortin-oi3o
|
But I haven\'t solved in contest, very disappointed\nNow i have 2 method ;\n1 Method:\n\nclass Solution {\npublic:\n int fillCups(vector<int>& a)\n {\n
|
Pathak_Ankit
|
NORMAL
|
2022-07-10T04:31:30.728674+00:00
|
2022-07-10T04:36:35.616534+00:00
| 465 | false |
But I haven\'t solved in contest, very disappointed\nNow i have 2 method ;\n1 Method:\n```\nclass Solution {\npublic:\n int fillCups(vector<int>& a)\n {\n int sum=0;\n for(auto e:a)\n {\n sum+=e;\n }\n return max(*max_element(a.begin(),a.end()),(sum+1)/2);\n }\n};\n```\n2 Method:\nSorting decreasing order and check first element\n```\nclass Solution {\npublic:\n int fillCups(vector<int>& a)\n {\n sort(a.begin(),a.end(),greater<int>());\n int count=0;\n while(a[0]>0)\n {\n a[0]--;\n a[1]--;\n count++;\n sort(a.begin(),a.end(),greater<int>());\n }\n return count;\n }\n};\n```
| 5 | 0 |
[]
| 1 |
minimum-amount-of-time-to-fill-cups
|
C++ || priority queue
|
c-priority-queue-by-soba_1-andw
|
\nclass Solution {\npublic:\n int fillCups(vector<int>& a) {\n int n = a.size();\n \n priority_queue<int> pq;\n \n for(aut
|
Soba_1
|
NORMAL
|
2022-07-10T04:04:28.388037+00:00
|
2022-07-12T13:45:07.345949+00:00
| 579 | false |
```\nclass Solution {\npublic:\n int fillCups(vector<int>& a) {\n int n = a.size();\n \n priority_queue<int> pq;\n \n for(auto &x: a){\n if(x != 0) pq.push(x);\n }\n int ans = 0;\n while(pq.size() >= 2){\n int x = pq.top();\n pq.pop();\n int y = pq.top();\n pq.pop();\n \n ans++;\n \n if(x-1 != 0) pq.push(x-1);\n if(y-1 != 0) pq.push(y-1); \n }\n \n if(!pq.empty()) ans += pq.top();\n \n return ans;\n }\n};\n```\n*note : There are only 3 elements in array*\n\n**M2**\n```\nclass Solution {\npublic:\n int fillCups(vector<int>& a) {\n sort(a.begin(),a.end());\n int sum=a[0]+a[1]+a[2];\n if(a[1]+a[0]>=a[2])sum=(sum+1)/2;\n else sum=a[2];return sum;\n }\n};\n```\n\n**M3**\n```\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n int ans=0;\n while(1) {\n sort(amount.begin(), amount.end());\n if (amount.back()<=0)\n break;\n \n amount[1]--, amount[2]--;\n ans++;\n }\n return ans;\n }\n};\n```
| 5 | 0 |
['C', 'Heap (Priority Queue)']
| 1 |
minimum-amount-of-time-to-fill-cups
|
SIMPLE MAX-HEAP C++ COMMENTED SOLUTION
|
simple-max-heap-c-commented-solution-by-zln6r
|
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
|
Jeffrin2005
|
NORMAL
|
2024-08-02T09:59:40.138257+00:00
|
2024-08-02T09:59:40.138293+00:00
| 272 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n\n\nclass Solution {\npublic:\n int fillCups(vector<int>& amount){\n // Create a max heap to always process the type of cup with the maximum remaining amount first\n priority_queue<int> maxHeap;\n for(auto&a : amount){\n if(a > 0) maxHeap.push(a);\n }\n int sec = 0;\n // Process the heap until all cups are filled\n while(!maxHeap.empty()){\n int first = 0;\n int second = 0;\n // Take the top element (the largest one) \n if(!maxHeap.empty()){\n first = maxHeap.top();\n maxHeap.pop();\n } // we can fill 2 cups at a time\n // Take the next top element if available\n if (!maxHeap.empty()) {\n second = maxHeap.top();\n maxHeap.pop();\n }\n // Increment the number of seconds\n sec++;\n // Decrease the count of these types and push back if still needed\n if (--first > 0) maxHeap.push(first);\n if (--second > 0) maxHeap.push(second);\n }\n \n return sec;\n }\n};\n```
| 4 | 0 |
['C++']
| 0 |
minimum-amount-of-time-to-fill-cups
|
Java Easy to Undersatnd || Simeple O(1) Solution || Without using extra space || 3 line solution
|
java-easy-to-undersatnd-simeple-o1-solut-65s2
|
Approach:\n\n1. First of all calculate the sum of all three elements and assign it to a variable (i.e sum).\n2. Find the max among all three element and assign
|
ravikdubey360
|
NORMAL
|
2022-07-16T05:57:48.462886+00:00
|
2022-07-22T20:28:17.324752+00:00
| 335 | false |
**Approach:**\n\n1. First of all calculate the **sum** of all three elements and assign it to a variable (i.e sum).\n2. Find the **max** among all three element and assign it to a variable (i.e mv).\n3. Return the **max** of **mv** and **(sum+1)/2** using the **Math.max()** method.\n\n\n**Code:**\n\n```\nint sum = amount[0]+amount[1]+amount[2];\nint mv = Math.max(amount[0],Math.max(amount[1],amount[2]));\nreturn Math.max(mv,(sum+1)/2);\n```
| 4 | 0 |
['Greedy', 'Java']
| 1 |
minimum-amount-of-time-to-fill-cups
|
JAVA | Simple Solution | Sorting | Recursion
|
java-simple-solution-sorting-recursion-b-lqwc
|
\n\tpublic int fillCups(int[] amount) {\n \n Arrays.sort(amount);\n\t\t\n if(amount[2] == 0) return 0;\n\t\t\n if(amount[1] == 0) re
|
KabraKrishna
|
NORMAL
|
2022-07-13T18:19:47.013346+00:00
|
2022-07-13T18:19:47.013374+00:00
| 341 | false |
```\n\tpublic int fillCups(int[] amount) {\n \n Arrays.sort(amount);\n\t\t\n if(amount[2] == 0) return 0;\n\t\t\n if(amount[1] == 0) return amount[2];\n else {\n\t\t\n amount[1] -= 1;\n amount[2] -= 1;\n return 1 + fillCups(amount);\n }\n }\n```
| 4 | 0 |
['Recursion', 'Java']
| 0 |
minimum-amount-of-time-to-fill-cups
|
[Python 1 line] Simplest Intuition Possible O(n)|O(1)
|
python-1-line-simplest-intuition-possibl-aghn
|
There are many people still confused about this one. So I will try to explain it as easily as possible.\nThink of it in real life. You have many cups and you ha
|
surajajaydwivedi
|
NORMAL
|
2022-07-10T18:04:00.754523+00:00
|
2022-07-10T18:09:52.727687+00:00
| 501 | false |
There are many people still confused about this one. So I will try to explain it as easily as possible.\nThink of it in real life. You have many cups and you have 2 taps.\n\n**Simple thing you will actually do**\nUse both the taps as long as you can. Just put a cup under each tap and keep filling water Replacing one cup for another. This will take **ceil(Total cups/2)** time. As you will fill 2 cups at once.\n\nThis *nearly* works.\nBut thing is, you can not use both taps for same temperature of water.\nNow before overanalyzing the issue, simply realise that this can be a problem if there is a requirement of a specific cup(let\'s say *hot*) more than **ceil(Total cups/2)** times. Otherwise, you will keep filling it whenever 1 tap is free.\n\nSo in this scenario, you will need time needed to **at least** fill those *hot* cups. As you will use one tap **only** for filling hot water. And with 1 tap you will fill the rest two types of cups. You can be sure that other two cups combined will not take more time as *one cup is more than half of requirement* (> ceil(Total cups/2) )\n\nSo answer is always\nmax( max(cups), ceil(Total cups/2)) )\n\nAccepted code,\n```\ndef fillCups(self, amount: List[int]) -> int:\n return max(int(math.ceil(sum(amount)/2)),max(amount))\n```
| 4 | 0 |
['Python']
| 1 |
minimum-amount-of-time-to-fill-cups
|
Easy to Understand Solution | Beats 100% | TC: O(1) SC: O(1)
|
easy-to-understand-solution-beats-100-tc-a5df
|
Find the cup that will take the maximum time. If its time is greater than the combined time taken by the other cups, then it is the minimum amount of time requi
|
fxce
|
NORMAL
|
2023-11-08T09:29:01.627079+00:00
|
2023-11-08T09:36:59.856516+00:00
| 229 | false |
Find the cup that will take the maximum time. If its time is greater than the combined time taken by the other cups, then it is the minimum amount of time required to fill all three cups.\n\n# Complexity\n- Time complexity: O(1)\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution {\n public int fillCups(int[] amount) {\n int max = Math.max(Math.max(amount[0], amount[1]), amount[2]);\n\n int sum = amount[0] + amount[1] + amount[2];\n\n if(max >= sum - max){\n return max;\n }\n \n return (sum + 1)/2;\n }\n}\n```
| 3 | 0 |
['Java']
| 0 |
minimum-amount-of-time-to-fill-cups
|
C++, simple, priority queue
|
c-simple-priority-queue-by-arif-kalluru-5ayb
|
Code\n\n// To minimize time, choose the two largest value and decrease it by 1.\n// Repeat this until all elements become zero.\nclass Solution {\npublic:\n
|
Arif-Kalluru
|
NORMAL
|
2023-06-06T16:01:03.168379+00:00
|
2023-06-06T16:01:03.168404+00:00
| 320 | false |
# Code\n```\n// To minimize time, choose the two largest value and decrease it by 1.\n// Repeat this until all elements become zero.\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n priority_queue<int> pq(amount.begin(), amount.end()); \n \n int time = 0;\n while (pq.top() > 0) {\n int num1 = pq.top(); pq.pop();\n int num2 = pq.top(); pq.pop();\n num1--;\n num2--;\n pq.push(num1);\n pq.push(num2);\n time++;\n }\n \n return time;\n }\n};\n```
| 3 | 0 |
['Array', 'Greedy', 'Sorting', 'Heap (Priority Queue)', 'C++']
| 0 |
minimum-amount-of-time-to-fill-cups
|
My DP Solution || No Maths || Brute force approach || Memoised || Overkill
|
my-dp-solution-no-maths-brute-force-appr-u3b1
|
Intuition\n Describe your first thoughts on how to solve this problem. \nWe have 6 choices that we can make, each recursive call takes that choice and returns t
|
2uringTested
|
NORMAL
|
2023-05-10T07:19:21.496050+00:00
|
2023-05-10T07:23:05.654233+00:00
| 170 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe have 6 choices that we can make, each recursive call takes that choice and returns the minimum number of seconds that it would take to get the cups filled from there.\n\nif any choice taken results in invalid quantity in any cup, which is negative quantity then we return a large value so that it wouldnt be considered in the minimum count.\n\nAs 3 independent states are being changed, we have used a 3D Matrix for the memoisation.\n\n# Complexity\n\nThe time complexity of the code without any memoisation would be \n$$O(6^n)$$ where $$ n = max(cold,warm,hot) $$\n\nAfter the memoisation the time complexity reduces greatly to $$O(cold*warm*hot)$$\n\n\n# Code\n```\nclass Solution {\npublic:\n int helper(int cold, int warm, int hot, vector<vector<vector<int>>>& dp){\n if(cold<0 || warm<0 || hot<0){\n return INT_MAX-1000;\n }\n if(cold==0 && warm==0 && hot==0){\n return 0;\n }\n if(dp[cold][warm][hot] != -1){\n return dp[cold][warm][hot];\n }\n\n int res1 = 1+helper(cold-1,warm-1,hot,dp);\n int res2 = 1+helper(cold-1,warm,hot-1,dp);\n int res3 = 1+helper(cold,warm-1,hot-1,dp);\n int res4 = 1+helper(cold-1,warm,hot,dp);\n int res5 = 1+helper(cold,warm-1,hot,dp);\n int res6 = 1+helper(cold,warm,hot-1,dp);\n\n return dp[cold][warm][hot]=min({res1,res2,res3,res4,res5,res6});\n }\n int fillCups(vector<int>& amount) {\n vector<vector<vector<int>>> dp(amount[0]+1, vector<vector<int>>(amount[1]+1, vector<int>(amount[2]+1, -1)));\n return helper(amount[0],amount[1],amount[2],dp);\n }\n};\n\n```
| 3 | 0 |
['Dynamic Programming', 'Memoization', 'C++']
| 0 |
minimum-amount-of-time-to-fill-cups
|
A Beginner Friendly Java Solution
|
a-beginner-friendly-java-solution-by-mou-dqf9
|
A solution for complete beginners...\nPlease upvote if it helps!\n\n# Code\n\nclass Solution {\n public int fillCups(int[] arr) {\n PriorityQueue<Inte
|
Mouktika
|
NORMAL
|
2023-03-11T11:43:09.438632+00:00
|
2023-03-11T12:52:13.838535+00:00
| 372 | false |
A solution for complete beginners...\nPlease upvote if it helps!\n\n# Code\n```\nclass Solution {\n public int fillCups(int[] arr) {\n PriorityQueue<Integer> max = new PriorityQueue<>(Collections.reverseOrder());\n\n for(int i : arr) max.add(i);\n\n int count = 0;\n while(max.peek() > 0) {\n int num1 = max.poll();\n int num2 = max.poll();\n max.add(--num1);\n max.add(--num2);\n count++;\n }\n \n return count;\n }\n}\n```
| 3 | 0 |
['Array', 'Greedy', 'Heap (Priority Queue)', 'Java']
| 0 |
minimum-amount-of-time-to-fill-cups
|
C++ Solution || Easy to Understand || 100% Faster
|
c-solution-easy-to-understand-100-faster-xbvz
|
\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n priority_queue<int> pq;\n for(int i=0;i<3;i++)\n {\n pq.p
|
01_Unzila
|
NORMAL
|
2023-02-26T04:22:59.153388+00:00
|
2023-02-26T04:22:59.153425+00:00
| 285 | false |
```\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n priority_queue<int> pq;\n for(int i=0;i<3;i++)\n {\n pq.push(amount[i]);\n }\n \n int count=0;\n while(pq.top()!=0)\n {\n int num1=pq.top();\n num1-=1;\n pq.pop();\n int num2=pq.top();\n num2-=1;\n pq.pop();\n \n pq.push(num1);\n pq.push(num2);\n \n count++;\n }\n \n return count;\n }\n};\n```
| 3 | 0 |
['C', 'Heap (Priority Queue)']
| 0 |
minimum-amount-of-time-to-fill-cups
|
Golang - solution based on sorting
|
golang-solution-based-on-sorting-by-tucu-3qdd
|
\nfunc fillCups(amount []int) int {\n sort.Ints(amount)\n a, b := amount[0] + amount[1], amount[2]\n if a < b {\n return b\n }\n return b
|
tucux
|
NORMAL
|
2022-09-28T10:51:09.180832+00:00
|
2022-09-28T10:51:09.180879+00:00
| 67 | false |
```\nfunc fillCups(amount []int) int {\n sort.Ints(amount)\n a, b := amount[0] + amount[1], amount[2]\n if a < b {\n return b\n }\n return b + (a - b + 1) / 2\n}\n```
| 3 | 0 |
['Go']
| 0 |
minimum-amount-of-time-to-fill-cups
|
Java Brute-Force Solution using Sorting
|
java-brute-force-solution-using-sorting-1m5cd
|
The observation is that we can get the minimum time needed if we always start with the maximum number of cups.\n- Since the array has a length of 3, I figure we
|
yupengchen
|
NORMAL
|
2022-08-26T23:53:24.338133+00:00
|
2023-01-05T17:57:47.094236+00:00
| 264 | false |
- The observation is that we can get the minimum time needed if we always start with the maximum number of cups.\n- Since the array has a length of 3, I figure we can just sort it everytime.\n```\nclass Solution {\n public int fillCups(int[] amount) {\n int cnt = 0;\n Arrays.sort(amount);\n while(amount[2] != 0){\n cnt++;\n amount[2] -= 1;\n amount[1] -= 1;\n Arrays.sort(amount);\n }\n return cnt;\n }\n}\n```
| 3 | 0 |
['Java']
| 0 |
minimum-amount-of-time-to-fill-cups
|
Simple Math O(1) solution
|
simple-math-o1-solution-by-nitu_pal-6gw8
|
It is so obvious that of max element is greater than sum of other 2 elements then it would take max element seconds. for eg 5,21, here 5>2+1, so 3 cups out of 5
|
Nitu_Pal
|
NORMAL
|
2022-07-17T19:28:45.290192+00:00
|
2022-07-17T19:28:45.290222+00:00
| 183 | false |
* It is so obvious that of max element is greater than sum of other 2 elements then it would take max element seconds. for eg 5,21, here 5>2+1, so 3 cups out of 5 cups will get filled with other 2 sets in 3 second and remaining 2 will take 2 seconds.\n* Now for the second case, 5,4,4. the answer will be (5+4+4)/2 +1=7. here is the explanation we are cosidering 2 cups at a time, because 2 cups will take 1 seconds and hence n cups will take n/2 seconds to get filled if n is odd it will take one extra second to fill it.\n* hope its understandable\n* below is the code !\n\n\n```\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n int a=amount[0],b=amount[1],c=amount[2];\n int d=max(a,max(b,c));\n if(2*d>a+b+c) return d;\n if((a+b+c)%2==0) return (a+b+c)/2;\n return (a+b+c)/2 +1;\n }\n};\n```
| 3 | 0 |
[]
| 0 |
minimum-amount-of-time-to-fill-cups
|
C++ || Easy Solution
|
c-easy-solution-by-thegentlemen-mc0f
|
Upvote toh banta hai\n\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n //basic cases\n if(amount[1]+amount[2]+amount[3]==1)r
|
TheGentlemen
|
NORMAL
|
2022-07-10T21:20:31.035801+00:00
|
2022-07-10T21:21:51.563496+00:00
| 152 | false |
***Upvote toh banta hai***\n```\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n //basic cases\n if(amount[1]+amount[2]+amount[3]==1)return 1;\n if(amount[1]+amount[2]+amount[3]==0)return 0;\n\t\t\n priority_queue<int>pq;\n \n\t\t//pushing element in queue\n for(int i=0;i<3;i++)\n {\n pq.push(amount[i]);\n }\n\t\t//initializing return variable;\n int count=0;\n\t\t\n while(pq.top()!=0)\n {\n //for cases [5,4,4] then n=5 and m=4\n int n=pq.top(); pq.pop(); int m=pq.top();\n\t\t\t\t//for cases [5,0,0] n=5 and m=0 so we add 5 to final answer\n if(m==0){ \n count+=n;\n break;}\n else{\n pq.pop();\n\t\t\t\t //reducing each by 1 and pushing in priority queue\n pq.push(n-1);\n pq.push(m-1);\n }\n\t\t\t\t //and adding the repetitions to the answer\n count++;\n }\n return count;\n }\n};\n```
| 3 | 0 |
['Heap (Priority Queue)']
| 0 |
minimum-amount-of-time-to-fill-cups
|
Easy C++ || MaxHeap Solution
|
easy-c-maxheap-solution-by-chavananiket3-zor0
|
\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n priority_queue<int> q;\n for(auto i:amount)\n q.push(i);\n
|
chavananiket38
|
NORMAL
|
2022-07-10T13:56:52.408762+00:00
|
2022-07-10T13:56:52.408794+00:00
| 156 | false |
```\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n priority_queue<int> q;\n for(auto i:amount)\n q.push(i);\n \n int ans = 0;\n while(q.top()!=0){\n int a = q.top();\n q.pop();\n int b = q.top();\n q.pop();\n if(a>0 and b>0){\n q.push(--a);\n q.push(--b);\n ans++;\n }else{\n q.push(--a);\n q.push(b);\n ans++;\n }\n }\n \n return ans;\n }\n};\n```
| 3 | 0 |
['C', 'Heap (Priority Queue)']
| 0 |
minimum-amount-of-time-to-fill-cups
|
Simple Python solution with explanation
|
simple-python-solution-with-explanation-t5odp
|
Sort the list. \nEvery time take two max numbers and decrement them by one. Also increment count by one. \nIf only one non zero element present then add that nu
|
saurabhvarade0903
|
NORMAL
|
2022-07-10T11:43:50.503430+00:00
|
2024-09-12T08:58:48.035290+00:00
| 1,044 | false |
Sort the list. \nEvery time take two max numbers and decrement them by one. Also increment count by one. \nIf only one non zero element present then add that number to count and return the count. \nIf all are zero then return count. \n\n```\nimport math\nclass Solution:\n def fillCups(self, l: List[int]) -> int:\n l.sort()\n c=0\n while(sum(l)!=0):\n if(l[-1]!=0 and l[-2]!=0):\n l[-1]-=1\n l[-2]-=1\n c+=1\n\t\t\t\t\n\t\t\t# If only one non zero element present then add that number to count and return the count.\n elif(l[-2]==0 and l[-3]==0):\n return c+l[-1]\n\t\t\t\t\n\t\t\t#If all are zero then return count\n elif(sum(l)==0):\n return c\n \n l.sort()\n return c\n```\n\nupvote if you like it
| 3 | 0 |
['Array', 'Greedy', 'Sorting', 'Python', 'Python3']
| 0 |
minimum-amount-of-time-to-fill-cups
|
CPP
|
cpp-by-thakur6306-wluy
|
\n class Solution {\npublic:\n int fillCups(vector& amount) {\n sort(amount.begin(),amount.end()); \n int x=amount[0];\n int y=amount
|
thakur6306
|
NORMAL
|
2022-07-10T04:40:57.532422+00:00
|
2022-07-10T04:40:57.532451+00:00
| 129 | false |
\n class Solution {\npublic:\n int fillCups(vector<int>& amount) {\n sort(amount.begin(),amount.end()); \n int x=amount[0];\n int y=amount[1];\n int z=amount[2];\n int sum=x+y+z;\n if(x+y>z) return sum/2+sum%2;\n if(x==0 && y==0) return z;\n else return z;\n }\n};\n\n\n\n
| 3 | 0 |
['C++']
| 0 |
minimum-amount-of-time-to-fill-cups
|
Javascript
|
javascript-by-kasidi-bih2
|
\nvar fillCups = function(amount) {\n let total = 0;\n let max = 0;\n for (let i = 0; i < amount.length; i++) {\n max = Math.max(max, amount[i])
|
kasidi
|
NORMAL
|
2022-07-10T04:27:39.378806+00:00
|
2022-07-10T04:29:41.792318+00:00
| 264 | false |
```\nvar fillCups = function(amount) {\n let total = 0;\n let max = 0;\n for (let i = 0; i < amount.length; i++) {\n max = Math.max(max, amount[i]);\n total += amount[i];\n }\n\t\n\t// if max cups bigger or equal to the sum of remain two smaller cups, then max cups will cover all number of cups we needed.\n if (max >= total - max) return max;\n return Math.ceil(total / 2);\n};\n```
| 3 | 0 |
['JavaScript']
| 0 |
minimum-amount-of-time-to-fill-cups
|
Greedy with priority queue
|
greedy-with-priority-queue-by-nadaralp-i4f6
|
We can approach this greedily.\n\nAlways try to fill up 2 different cups, if we can\'t fill 2 different cups it means we have only 1 cup left to fill with X fil
|
nadaralp
|
NORMAL
|
2022-07-10T04:20:29.785978+00:00
|
2022-07-10T04:20:29.786005+00:00
| 440 | false |
We can approach this greedily.\n\nAlways try to fill up 2 different cups, if we can\'t fill 2 different cups it means we have only 1 cup left to fill with X fills.\n\nWe need to fill the cups that have the most capcity greedily, this will allow us to fill 2 cups for as long as possible.\n\nWhen we are left with 1 cup, just add the capacity to the result since we can only fill it 1 move at a time.\n\n# Code\n```\nfrom heapq import heapify, heappop, heappush\n\nclass Solution:\n def fillCups(self, amount: List[int]) -> int:\n moves = 0\n max_heap = [-v for v in amount]\n heapify(max_heap)\n \n while max_heap:\n biggest = heappop(max_heap)\n \n if max_heap and max_heap[0] != 0:\n moves += 1\n second_biggest = heappop(max_heap)\n \n biggest += 1\n second_biggest += 1\n \n if biggest != 0: heappush(max_heap, biggest)\n if second_biggest != 0: heappush(max_heap, second_biggest)\n \n else:\n moves += (-biggest)\n \n return moves\n \n```
| 3 | 0 |
['Greedy', 'Python']
| 1 |
minimum-amount-of-time-to-fill-cups
|
Easy || simple C++ Solution
|
easy-simple-c-solution-by-honeybist2002-un67
|
\n\nint fillCups(vector<int>& a) {\n int n=a.size();\n sort(a.begin(),a.end());\n if(a[0]==0 && a[1]==0 && a[2]!=0) return a[2];\n \
|
honeybist2002
|
NORMAL
|
2022-07-10T04:17:45.715900+00:00
|
2022-07-10T04:17:45.715938+00:00
| 39 | false |
\n```\nint fillCups(vector<int>& a) {\n int n=a.size();\n sort(a.begin(),a.end());\n if(a[0]==0 && a[1]==0 && a[2]!=0) return a[2];\n \n int ans=0;\n while(true){\n if(a[0]==0 && a[1]==0 && a[2]==0) return ans;\n sort(a.begin(),a.end());\n reverse(a.begin(),a.end());\n ans+=1;\n a[0]=a[0]-1;\n if(a[1]!=0) a[1]=a[1]-1;\n }\n return ans;\n }\n```
| 3 | 0 |
[]
| 0 |
minimum-amount-of-time-to-fill-cups
|
C++ Easy Solution Two Approaches || Constant space and Heap
|
c-easy-solution-two-approaches-constant-8i3ef
|
Approach 1 ---> Priority Queue\n\nclass Solution {\npublic:\n int fillCups(vector<int>& arr) {\n int count=0; \n priority_queue<int>pq(a
|
Shyamji07
|
NORMAL
|
2022-07-10T04:03:40.874329+00:00
|
2022-07-10T04:03:40.874355+00:00
| 177 | false |
**Approach 1 ---> Priority Queue**\n```\nclass Solution {\npublic:\n int fillCups(vector<int>& arr) {\n int count=0; \n priority_queue<int>pq(arr.begin(),arr.end());\n while(pq.top()!=0){\n int t1=pq.top();\n pq.pop();\n int t2=pq.top();\n pq.pop();\n pq.push(t1-1);\n pq.push(t2-1);\n count++;\n }\n return count;\n }\n};\n```\n\n**Approach 2 --> Constant Space**\n\n```\nclass Solution {\npublic:\n int fillCups(vector<int>& arr) {\n sort(arr.begin(),arr.end()); \n int x=arr[0], y=arr[1],z=arr[2]; \n int sum=x+y+z; \n if(x+y>z)return sum/2+sum%2; \n if(x==0 && y==0)return z; \n else return z; \n } \n \n};\n```
| 3 | 0 |
['C', 'Heap (Priority Queue)', 'C++']
| 0 |
minimum-amount-of-time-to-fill-cups
|
Python: MaxHeap
|
python-maxheap-by-aditya_kathpalia-mh94
|
IntuitionWe need the top 2 cups at any timeApproachUse a max heap to keep track of the top 2 types of cup at any secondCode
|
aditya_kathpalia
|
NORMAL
|
2025-03-10T06:02:56.102209+00:00
|
2025-03-10T06:02:56.102209+00:00
| 77 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
We need the top 2 cups at any time
# Approach
<!-- Describe your approach to solving the problem. -->
Use a max heap to keep track of the top 2 types of cup at any second
# Code
```python3 []
class Solution:
def fillCups(self, amount: List[int]) -> int:
heap = []
for i in amount:
if i != 0:
heapq.heappush(heap, -i)
resp = 0
while heap:
print(heap)
if len(heap) >= 2:
x1 = -heapq.heappop(heap)
x2 = -heapq.heappop(heap)
x1 -= 1
x2 -= 1
if x1 != 0:
heapq.heappush(heap, -x1)
if x2 != 0:
heapq.heappush(heap, -x2)
resp += 1
else:
x1 = -heapq.heappop(heap)
resp += x1
return resp
```
| 2 | 0 |
['Python3']
| 0 |
minimum-amount-of-time-to-fill-cups
|
Easy C++ solution
|
easy-c-solution-by-geethanjali_37-fwaz
|
Intuition\nThe problem requires us to minimize the time needed to fill cups with three different amounts of liquid. The idea is to always try to reduce the two
|
geethanjali_37
|
NORMAL
|
2024-09-17T09:01:45.317855+00:00
|
2024-09-17T09:01:45.317884+00:00
| 66 | false |
# Intuition\nThe problem requires us to minimize the time needed to fill cups with three different amounts of liquid. The idea is to always try to reduce the two largest amounts simultaneously to minimize the total time.\n\n# Approach\n\nInitialization: Start with a counter cnt set to 0.\nLoop until all amounts are zero: Use a while loop to continue until all three amounts are zero.\nDecrement the two largest amounts: In each iteration, identify the two largest amounts and decrement them.\nIncrement the counter: Increase the counter in each iteration to count the time steps.\nReturn the counter: Once all amounts are zero, return the counter as the result.\n\n# Complexity\n\n**Time complexity**: The time complexity is O(nlogn)\n due to the sorting operation inside the loop. However, since the number of elements is fixed at 3, this can be considered as O(1)\n in practical terms.\n**Space complexity**: The space complexity is O(1)\n> as we are using a fixed amount of extra space.\n# Code\n```cpp []\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n int cnt=0;\n // sort(amount.begin(),amount.end());\n while(amount[0]>0||amount[1]>0||amount[2]>0)\n {\n if(amount[0]>=amount[2]&&amount[1]>=amount[2])\n {\n amount[0]-=1;\n amount[1]-=1;\n }\n else if(amount[0]>=amount[1]&&amount[2]>=amount[1])\n {\n amount[0]-=1;\n amount[2]-=1;\n }\n else if(amount[1]>=amount[0]&&amount[2]>=amount[0])\n {\n amount[1]-=1;\n amount[2]-=1;\n }\n cnt++;\n }\n return cnt;\n }\n};
| 2 | 0 |
['C++']
| 0 |
minimum-amount-of-time-to-fill-cups
|
[Java] Easy 100% solution
|
java-easy-100-solution-by-ytchouar-yz79
|
java\nclass Solution {\n public int fillCups(final int[] amount) {\n int first = 0, second = 0, third = 0;\n\n if(amount[0] >= amount[1] && amo
|
YTchouar
|
NORMAL
|
2024-05-02T04:44:51.499591+00:00
|
2024-05-02T04:44:51.499625+00:00
| 337 | false |
```java\nclass Solution {\n public int fillCups(final int[] amount) {\n int first = 0, second = 0, third = 0;\n\n if(amount[0] >= amount[1] && amount[0] >= amount[2]) {\n first = amount[0];\n\n if(amount[1] >= amount[2]) {\n second = amount[1];\n third = amount[2];\n } else {\n second = amount[2];\n third = amount[1];\n }\n } else if(amount[1] >= amount[0] && amount[1] >= amount[2]) {\n first = amount[1];\n\n if(amount[0] >= amount[2]) {\n second = amount[0];\n third = amount[2];\n } else {\n second = amount[2];\n third = amount[0];\n }\n } else {\n first = amount[2];\n\n if(amount[0] >= amount[1]) {\n second = amount[0];\n third = amount[1];\n } else {\n second = amount[1];\n third = amount[0];\n }\n }\n\n return Math.max(first, (first + second + third + 1) / 2);\n }\n}\n```
| 2 | 0 |
['Java']
| 0 |
minimum-amount-of-time-to-fill-cups
|
[C++] || Easy Solution using priority queue || 0 ms(Beats 100.00%) ✅
|
c-easy-solution-using-priority-queue-0-m-fgor
|
\n\n# Code\n\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n priority_queue<int> pq;\n for(auto x:amount){\n if(x
|
C0derX
|
NORMAL
|
2024-03-22T20:27:16.735367+00:00
|
2024-03-22T20:27:16.735385+00:00
| 159 | false |
\n\n# Code\n```\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n priority_queue<int> pq;\n for(auto x:amount){\n if(x)\n pq.push(x);\n }\n\n int ans=0;\n\n while(pq.size()>1){\n int a=pq.top();\n pq.pop();\n int b=pq.top();\n pq.pop();\n if(a>1)\n pq.push(a-1);\n if(b>1)\n pq.push(b-1);\n\n ans++;\n }\n\n return pq.empty()?ans:ans+pq.top();\n }\n};\n```
| 2 | 0 |
['Array', 'Heap (Priority Queue)', 'C++']
| 0 |
minimum-amount-of-time-to-fill-cups
|
Beats 100%🔥|| easy JAVA Solution✅
|
beats-100-easy-java-solution-by-priyansh-zeo5
|
Code\n\nclass Solution {\n public int fillCups(int[] nums) {\n int ans=0;\n while(true){\n if(nums[0]<=0 && nums[1]<=0 && nums[2]<=0
|
priyanshu1078
|
NORMAL
|
2024-02-13T21:36:51.402172+00:00
|
2024-02-13T21:36:51.402192+00:00
| 205 | false |
# Code\n```\nclass Solution {\n public int fillCups(int[] nums) {\n int ans=0;\n while(true){\n if(nums[0]<=0 && nums[1]<=0 && nums[2]<=0) break;\n if(nums[0]>=nums[1] && nums[2]>=nums[1]){\n ans++;\n nums[0]--;\n nums[2]--;\n }else if(nums[0]>=nums[2] && nums[1]>=nums[2]){\n ans++;\n nums[0]--;\n nums[1]--;\n }else{\n ans++;\n nums[1]--;\n nums[2]--;\n }\n }\n return ans;\n }\n}\n```
| 2 | 0 |
['Greedy', 'Java']
| 0 |
minimum-amount-of-time-to-fill-cups
|
C++ || easy ||pq
|
c-easy-pq-by-shradhaydham24-5ckf
|
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
|
shradhaydham24
|
NORMAL
|
2023-07-29T20:51:43.017120+00:00
|
2023-07-29T20:51:43.017140+00:00
| 633 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int fillCups(vector<int>& am) \n {\n priority_queue<int> pq;\n for(auto i :am)\n {\n pq.push(i);\n }\n int count=0;\n while(pq.top()!=0)\n {\n int a=pq.top();\n pq.pop();\n int b=pq.top();\n pq.pop();\n a--;\n b--;\n pq.push(a);\n pq.push(b);\n count++;\n }\n return count;\n }\n};\n```
| 2 | 0 |
['C++']
| 0 |
minimum-amount-of-time-to-fill-cups
|
Beats 100% in time || Priority queue C++ code
|
beats-100-in-time-priority-queue-c-code-j019t
|
\n\n# Code\n\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n priority_queue<int> pq;\n for(int i=0; i<3; i++){\n
|
guptabakul21
|
NORMAL
|
2023-06-21T14:29:34.998897+00:00
|
2023-06-21T14:29:34.998924+00:00
| 565 | false |
\n\n# Code\n```\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n priority_queue<int> pq;\n for(int i=0; i<3; i++){\n pq.push(amount[i]);\n }\n int time=0;\n while(pq.top() != 0){\n time += 1;\n int temp = pq.top()-1;\n pq.pop();\n int temp2 = pq.top()-1;\n pq.pop();\n pq.push(temp);\n pq.push(temp2);\n }\n return time;\n }\n};\n```
| 2 | 0 |
['Heap (Priority Queue)', 'C++']
| 0 |
minimum-amount-of-time-to-fill-cups
|
✅✔️Easy implementation using priority queue || max Heap✈️✈️✈️✈️✈️
|
easy-implementation-using-priority-queue-v53b
|
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
|
ajay_1134
|
NORMAL
|
2023-06-14T14:21:32.957035+00:00
|
2023-06-14T14:21:32.957053+00:00
| 117 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n priority_queue<int>pq;\n for(auto i : amount){\n if(i > 0) pq.push(i);\n }\n int ans = 0;\n while(pq.size() > 1){\n int type1 = pq.top(); pq.pop();\n int type2 = pq.top(); pq.pop();\n type1--; type2--;\n if(type1 > 0) pq.push(type1);\n if(type2 > 0) pq.push(type2);\n ans++;\n }\n if(!pq.empty()) ans += pq.top();\n return ans;\n }\n};\n```
| 2 | 0 |
['Heap (Priority Queue)', 'C++']
| 1 |
minimum-amount-of-time-to-fill-cups
|
✅ SIMPLE C++ SOLUTION || WELL COMMENTED || USING PRIORITY QUEUE
|
simple-c-solution-well-commented-using-p-jd4i
|
Code\n\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n int seconds = 0;\n priority_queue<int> pq;\n // pushing all th
|
ammarkhan575
|
NORMAL
|
2023-05-26T16:38:49.488143+00:00
|
2023-05-26T16:38:49.488190+00:00
| 332 | false |
# Code\n```\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n int seconds = 0;\n priority_queue<int> pq;\n // pushing all three amount in max heap\n pq.push(amount[0]);\n pq.push(amount[1]);\n pq.push(amount[2]);\n // increase the seconds while any cup is left\n while(pq.top()>0){\n // check the 1st cup \n int first;\n first = pq.top();\n pq.pop();\n int second;\n // if 2nd cup is left then fill both the cup which take one second\n if(pq.top()>0){\n second = pq.top();\n pq.pop();\n }\n else{\n // if only single type of cup is left than consider one second for each cup\n // and add it to the seconds \n if(first>0)\n seconds+=first;\n break;\n }\n pq.push(first-1);\n pq.push(second-1);\n seconds++;\n }\n return seconds;\n }\n};\n```
| 2 | 0 |
['C++']
| 1 |
minimum-amount-of-time-to-fill-cups
|
Simple Approach || Priority_Queue || Explanation || c++
|
simple-approach-priority_queue-explanati-s61f
|
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
|
tanveer_965
|
NORMAL
|
2023-05-17T19:34:29.699093+00:00
|
2023-05-17T19:41:40.831052+00:00
| 588 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n// AT PARTICULAR INSTANCE WE TAKE GREATEST 2 ELEMENT AND DECRESE ITS VALUE BY 1 AND AGAIN PUSHED IN THE QUEUE\n// THEREFORE IF THE SIZE OF QUEUE IS 1 THEN WE CANT TAKE OUT TWO ELEMENT THEREFORE WE HAVE TO RUN THE LOOP TILL\n// SIZE IS GREATER THAN 2. AFTER DECREASING IF THE VALUE IS EQUAL TO ZERO THEN WE WILL NOT PUSH IN THE QUEUE\n// ALL THOUGH THE NUMBER OF WATER IS COMPLETED. \n int fillCups(vector<int>& amount) {\n priority_queue<int>pq;\n for(int i=0;i<3;i++)\n {\n if(amount[i]!=0) // [5,0,0,] TO AVOID THIS TYPE OF CASES. IF WE DONOT DO THIS STEP THEN SIZE OF \n pq.push(amount[i]);// QUEUE IS 3 THEN THE LOOP HAS BEEN STARTED AND AFTER TAKING TWO VALUE AND \n } // DECREASED THAT VALUE WE GET (4,-1) AND THEN INSERTED IN QUEUE THEN THE DECRESED VALUE \n int count=0; // WILL NEVER BE ZERO AND HENCE THE SIZE WILL NOT DECREASES ....INFINTE LOOP OCCUR\n while(pq.size()>1)\n {\n int top1 = pq.top();\n pq.pop();\n int top2 = pq.top();\n pq.pop();\n top1-=1;\n top2-=1;\n if(top1!=0)\n pq.push(top1);\n if(top2!=0)\n pq.push(top2);\n count++; \n }\n if(!pq.empty()) return count+pq.top();\n return count;\n\n OR \n\n priority_queue<int>pq(amount.begin(),amount.end());\n int count=0;\n while(pq.top()!=0)\n {\n int t1=pq.top();\n pq.pop();\n int t2=pq.top();\n pq.pop();\n pq.push(t1-1);\n pq.push(t2-1);\n count++;\n }\n return count;\n }\n};\n```
| 2 | 0 |
['C++']
| 1 |
minimum-amount-of-time-to-fill-cups
|
Minimum Amount of Time to Fill Cups Solution in C++
|
minimum-amount-of-time-to-fill-cups-solu-ofsn
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nBrute Force\n# Complexi
|
The_Kunal_Singh
|
NORMAL
|
2023-04-25T14:03:07.260113+00:00
|
2023-04-27T16:24:00.779761+00:00
| 449 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBrute Force\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2logn)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n int time=0;\n while(true)\n {\n sort(amount.begin(), amount.end());\n if(amount[2]>0)\n {\n amount[2]--;\n time++;\n }\n if(amount[1]>0)\n {\n amount[1]--;\n }\n else if(amount[2]==0)\n {\n break;\n }\n }\n return time;\n }\n};\n```\n# Approach\n<!-- Describe your approach to solving the problem. -->\nOptimized Approach\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n int time=0;\n time = max(*max_element(amount.begin(), amount.end()), (accumulate(amount.begin(), amount.end(), 0)+1)/2);\n return time;\n }\n};\n```\n\n
| 2 | 0 |
['C++']
| 0 |
minimum-amount-of-time-to-fill-cups
|
Fully Explained (O(1), O(1)), beats 100%
|
fully-explained-o1-o1-beats-100-by-stasi-pv9k
|
Intuition\nAt first, we sort the cups (we just need to find the biggest stack). If the biggest stack (0) is equal or bigger than the stacks left (1 and 2), it\'
|
Stasinos
|
NORMAL
|
2023-04-14T10:54:49.330771+00:00
|
2023-08-29T17:25:23.730507+00:00
| 291 | false |
# Intuition\nAt first, we sort the cups (we just need to find the biggest stack). If the biggest stack (0) is equal or bigger than the stacks left (1 and 2), it\'s pretty obvious that this will be the solution. If not, we simply have to pair cups from stacks 1 or 2 with cups from stack 0 till stack 0 has 0 cups, in such a way that we will be left with n and n or n+1 cups in stacks 1 and 2. This takes nums[2] + ceil((nums[0]+nums[1]-nums[2]+1)/2) steps, which is equal to ceil((nums[0]+nums[1]+nums[2]+1)/2).\n\n# Approach\nCase #1: nums[2] >= nums[0]+nums[1] :\nreturn nums[2];\nCase #2: nums[2] < nums[0]+nums[1] :\nreturn ceil((nums[0]+nums[1]+nums[2]+1)/2);\n\n# Complexity\n- Time complexity:\n# O(1)\n- Space complexity:\n# O(1)\n\n\n# Code\n```\nclass Solution {\npublic:\n int fillCups(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n return (nums[2] >= nums[0]+nums[1] ? nums[2] : ceil((nums[0]+nums[1]+nums[2]+1)/2));\n }\n};\n```\nIf this was helpful, drop a like. Happy coding!\n\n
| 2 | 0 |
['Math', 'C++']
| 1 |
minimum-amount-of-time-to-fill-cups
|
Java O(1)
|
java-o1-by-zeldox-m0hu
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nWe have to fill 2 cup a
|
zeldox
|
NORMAL
|
2022-11-15T20:37:02.941664+00:00
|
2022-11-15T20:37:02.941695+00:00
| 213 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe have to fill 2 cup at the same time so if our max cap 2 times bigger than sum we have to take it otherwise we have to remove cups 2 by 2 \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$because only 3 cup\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$because only 3 cup\n# Code\n```\nclass Solution {\n public int fillCups(int[] amount) {\n int maxCup = 0, sum = 0;\n for(int curCup: amount) {\n maxCup = Math.max(curCup, maxCup);\n sum += curCup;\n }\n return Math.max(maxCup, (sum + 1) / 2);\n }\n}\n```
| 2 | 0 |
['Java']
| 1 |
minimum-amount-of-time-to-fill-cups
|
Using Heap js solution
|
using-heap-js-solution-by-zeeshan_ali_mg-49hb
|
\n/**\n * @param {number[]} amount\n * @return {number}\n */\nvar fillCups = function (amount) {\n const q = new MaxPriorityQueue();\n for (let i = 0; i < amo
|
Zeeshan_Ali_MG
|
NORMAL
|
2022-10-26T03:44:10.436876+00:00
|
2022-10-26T03:44:10.436920+00:00
| 112 | false |
```\n/**\n * @param {number[]} amount\n * @return {number}\n */\nvar fillCups = function (amount) {\n const q = new MaxPriorityQueue();\n for (let i = 0; i < amount.length; i++) {\n q.enqueue(amount[i]);\n }\n\n let total = 0;\n while (true) {\n let a = q.dequeue().element;\n let b = q.dequeue().element;\n\n if (a == 0 || b == 0) {\n total = total + (a + b);\n return total;\n } else {\n total++;\n a--;\n b--;\n\n q.enqueue(a);\n q.enqueue(b);\n }\n }\n};\n\n```
| 2 | 0 |
['Heap (Priority Queue)', 'JavaScript']
| 0 |
minimum-amount-of-time-to-fill-cups
|
EASY TO UNDERSTAND || JAVA CODE
|
easy-to-understand-java-code-by-priyanka-4kwh
|
\nclass Solution {\n public int fillCups(int[] amount) {\n int sec=0;\n Arrays.sort(amount);\n while (amount[1]>0 && amount[2]>0){\n
|
priyankan_23
|
NORMAL
|
2022-08-29T21:11:23.612719+00:00
|
2022-08-29T21:11:23.612763+00:00
| 93 | false |
```\nclass Solution {\n public int fillCups(int[] amount) {\n int sec=0;\n Arrays.sort(amount);\n while (amount[1]>0 && amount[2]>0){\n amount[1]--;\n amount[2]--;\n Arrays.sort(amount); \n sec++;\n }\n while(amount[2]>0 ){\n amount[2]--;\n \n sec++;\n }\n return sec;\n }\n}\n```
| 2 | 0 |
[]
| 0 |
minimum-amount-of-time-to-fill-cups
|
[Python] Max heap - Greedy solution
|
python-max-heap-greedy-solution-by-gp05-hcob
|
\nclass Solution:\n def fillCups(self, amount: List[int]) -> int:\n # Greedy using priority queue\n heap = []\n for a in amount:\n
|
Gp05
|
NORMAL
|
2022-08-27T09:21:30.214195+00:00
|
2022-08-27T09:21:30.215952+00:00
| 91 | false |
```\nclass Solution:\n def fillCups(self, amount: List[int]) -> int:\n # Greedy using priority queue\n heap = []\n for a in amount:\n heapq.heappush(heap, -a)\n seconds = 0\n while heap[0] != 0:\n\t\t # get the max two cup\n max1 = heappop(heap)\n max2 = heappop(heap)\n seconds += 1\n heappush(heap, max1 + 1)\n heappush(heap, max2 + 1)\n\t\t\n return seconds\n```
| 2 | 0 |
['Python']
| 0 |
minimum-amount-of-time-to-fill-cups
|
JAVA☕ || 3 Liner Code✅ || Easy-UnderStanding
|
java-3-liner-code-easy-understanding-by-eoshg
|
DON\'T FORGET TO UPVOTE IT HELPS A LOT\n\nclass Solution {\n public int fillCups(int[] amount) {\n int max = Math.max(Math.max(amount[0],amount[1]),am
|
hirentimbadiya74
|
NORMAL
|
2022-08-13T18:16:30.730801+00:00
|
2022-08-14T07:58:44.148310+00:00
| 155 | false |
**DON\'T FORGET TO UPVOTE IT HELPS A LOT**\n```\nclass Solution {\n public int fillCups(int[] amount) {\n int max = Math.max(Math.max(amount[0],amount[1]),amount[2]);\n int sum = amount[0] + amount[1] + amount[2];\n return Math.max(max , (sum+1)/2);\n }\n}\n```\n**UPVOTE IF YOU LIKED SOLUTION**\n# UPVOTE
| 2 | 0 |
['Java']
| 0 |
minimum-amount-of-time-to-fill-cups
|
Swift | One-Liner | Fastest & Simplest | FULLY EXPLAINED
|
swift-one-liner-fastest-simplest-fully-e-aokv
|
One-Liner (accepted answer)\n\nclass Solution {\n func fillCups(_ amount: [Int]) -> Int {\n max(amount.max()!, amount.reduce(1,+)/2)\n }\n}\n\n\nSO
|
UpvoteThisPls
|
NORMAL
|
2022-08-03T06:33:40.127973+00:00
|
2022-08-03T06:49:50.040120+00:00
| 73 | false |
**One-Liner (accepted answer)**\n```\nclass Solution {\n func fillCups(_ amount: [Int]) -> Int {\n max(amount.max()!, amount.reduce(1,+)/2)\n }\n}\n```\n\n**SOLUTION EXPLANATION**\n\n**Approach**\n1) First, imagine the three element array is separated into three sorted values: Small, Medium and Large replace Cold, Warm, Hot.\n2) There are two cases to this problem:\n\t**Case 1: Largest element is at least the size of the two other elements combined.** (`Medium + Small <= Large`): \n\tSubtract the combined middle and smaller elements from the largest. These will pair up with the subtracted units, one per second. The remaining value of the largest will reduce by one unit every second. Since both slices of the largest element go away one unit per second, it doesn\'t matter what size or proportion of the slices are, the largest value is the number of seconds it will take for the cups to get filled up, so return that value.\n\t\n\t**Case 2: Largest element is smaller than the other two elements combined.** (`Medium + Small > Large`)\n\tThe difference between `(Medium - Small) < Large` (otherwise, Medium would become Large). We\'ll remove one unit at a time from Large and remove a pairing unit from the largest of Medium and Small values. When Large is exhausted, the difference between Medium and Small will be zero or one. So, the total number of seconds is determined by paring up all units of the three values (plus the odd-case). We can calculate this total number by adding up the original three values, add one to expose the odd-case and divide the sum by 2 (pairs) to get the number of seconds required to fill the cups. \n\n3) If we don\'t sort the array, we don\'t have access to Small, Medium or Large. This is OK, between the two cases, we calculate both of them and return the larger of the two values. When Case 1 is the case, the largest value in the array is at least the size of the calculation in Case 2, so return that. When Case 2 is the case, the largest value in the array doesn\'t contribute as much as half of all three values, so we can use the `max()` operator between the two cases to determine which case is active.
| 2 | 0 |
[]
| 0 |
minimum-amount-of-time-to-fill-cups
|
java fast solution
|
java-fast-solution-by-hurshidbek-wqjz
|
\nPLEASE UPVOTE IF YOU LIKE.\n\n int sum = a[0] + a[1] + a[2];\n int max = Math.max(a[0], Math.max(a[1], a[2]));\n \n if(2*max >= su
|
Hurshidbek
|
NORMAL
|
2022-07-29T08:09:03.829000+00:00
|
2022-08-20T13:21:50.841044+00:00
| 215 | false |
```\nPLEASE UPVOTE IF YOU LIKE.\n```\n int sum = a[0] + a[1] + a[2];\n int max = Math.max(a[0], Math.max(a[1], a[2]));\n \n if(2*max >= sum) return max;\n if(sum % 2 == 0) return sum / 2;\n \n return (sum / 2) + 1;
| 2 | 0 |
['Array', 'Java']
| 0 |
minimum-amount-of-time-to-fill-cups
|
| ! | Java Pure Brute Force Solution | ! |
|
java-pure-brute-force-solution-by-dracul-d46b
|
class Solution {\n public int fillCups(int[] amount) {\n int countSec=0;\n while(true){\n Arrays.sort(amount);\n if(amount[0]==
|
draculatapes
|
NORMAL
|
2022-07-27T15:07:09.930254+00:00
|
2022-07-27T15:07:09.930291+00:00
| 58 | false |
class Solution {\n public int fillCups(int[] amount) {\n int countSec=0;\n while(true){\n Arrays.sort(amount);\n if(amount[0]==0&&amount[1]==0&&amount[2]==0){\n break;\n }\n ++countSec; \n if(amount[1]>0)\n {\n amount[1]--;\n }\n if(amount[2]>0){\n amount[2]--;\n }\n } \n return countSec;\n }\n}
| 2 | 0 |
[]
| 0 |
minimum-amount-of-time-to-fill-cups
|
Fastest and Easy to Understand 7 line code
|
fastest-and-easy-to-understand-7-line-co-zdjj
|
\nclass Solution:\n def fillCups(self, amount: List[int]) -> int:\n time = 0\n \n while amount!= [0,0,0]:\n amount.sort()\n
|
naynishah6
|
NORMAL
|
2022-07-23T08:48:54.771247+00:00
|
2022-07-23T08:49:08.848349+00:00
| 190 | false |
```\nclass Solution:\n def fillCups(self, amount: List[int]) -> int:\n time = 0\n \n while amount!= [0,0,0]:\n amount.sort()\n if amount[-1] > 0:\n amount[-1] -=1\n if amount[-2] >0:\n amount[-2] -=1\n \n time+=1\n \n return(time)\n```
| 2 | 0 |
['Python']
| 1 |
minimum-amount-of-time-to-fill-cups
|
Python Solution || Easy to Understand
|
python-solution-easy-to-understand-by-wo-usp6
|
\nclass Solution:\n def fillCups(self, amount: List[int]) -> int:\n m,s = max(amount),sum(amount)\n return max(m,s//2+s%2)\n
|
workingpayload
|
NORMAL
|
2022-07-15T16:38:43.805793+00:00
|
2022-07-15T16:38:43.805864+00:00
| 126 | false |
```\nclass Solution:\n def fillCups(self, amount: List[int]) -> int:\n m,s = max(amount),sum(amount)\n return max(m,s//2+s%2)\n```
| 2 | 0 |
['Python']
| 0 |
minimum-amount-of-time-to-fill-cups
|
Java Simple Solution
|
java-simple-solution-by-hritikkesharwani-mlok
|
class Solution {\n public int fillCups(int[] amount) {\n int cold = amount[0];\n int warm = amount[1];\n int hot = amount[2];\n i
|
HritikKesharwani
|
NORMAL
|
2022-07-13T15:36:56.287404+00:00
|
2022-07-13T15:36:56.287440+00:00
| 174 | false |
```class Solution {\n public int fillCups(int[] amount) {\n int cold = amount[0];\n int warm = amount[1];\n int hot = amount[2];\n int ans = 0 ;\n while(cold > 0 || warm > 0 || hot > 0){\n if(cold >= warm && warm >= hot){\n cold--;\n warm--;\n ans++;\n }else if(cold >= warm && hot >= warm){\n cold--;\n hot--;\n ans++;\n }else if(warm >= cold && hot >= warm){\n hot--;\n warm--;\n ans++;\n }else if(warm>= cold && warm >= hot){\n warm--;\n if(cold > hot){\n cold--;\n }else{\n hot--;\n }\n ans++;\n }\n else if(warm == hot && hot == cold ){\n warm--;\n cold--;\n ans++;\n }\n \n }\n \n return ans;\n\t\t\n }\n}\n```
| 2 | 0 |
['Java']
| 0 |
minimum-amount-of-time-to-fill-cups
|
C++ easy to understand solution
|
c-easy-to-understand-solution-by-sb5-nu5e
|
\nint fillCups(vector<int>& amount) {\n int n=amount.size();\n sort(amount.begin(),amount.end());\n int cnt=0;\n while(amount[1]!=0)
|
sb5
|
NORMAL
|
2022-07-13T05:08:37.885580+00:00
|
2022-07-13T05:08:37.885622+00:00
| 64 | false |
```\nint fillCups(vector<int>& amount) {\n int n=amount.size();\n sort(amount.begin(),amount.end());\n int cnt=0;\n while(amount[1]!=0){\n amount[1]--;\n amount[2]--;\n cnt++;\n sort(amount.begin(),amount.end());\n }\n cnt+=amount[2];\n return cnt;\n }\n\t```\nSort the array then run the loop while the middle element of the array is not equal to 0 because then it wouldn\'t be able to make pairs with greater elements.\nEvery time the loop runs just subtract second highest and highest element by one when middle element becomes zero add the largest element to count variable. Don\'t forget to sort the array after each iteration of while loop.
| 2 | 0 |
['C', 'Sorting']
| 0 |
minimum-amount-of-time-to-fill-cups
|
✅ JavaScript Solution || Fast & Easy to understand || Simple
|
javascript-solution-fast-easy-to-underst-e3p3
|
\nvar fillCups = function(amount) {\n var count = 0\n var a = amount\n while (eval(a.join("+")) > 0) {\n var max = Math.max(...a)\n a.spl
|
PoeticIvy302543
|
NORMAL
|
2022-07-12T17:08:45.302218+00:00
|
2022-07-25T21:32:43.945852+00:00
| 259 | false |
```\nvar fillCups = function(amount) {\n var count = 0\n var a = amount\n while (eval(a.join("+")) > 0) {\n var max = Math.max(...a)\n a.splice(a.indexOf(max), 1)\n var max2 = Math.max(...a)\n a.splice(a.indexOf(max2), 1)\n count++\n if(max == 0) a.push(0)\n else a.push(max - 1)\n if (max2==0) a.push(0)\n else a.push(max2 - 1)\n } return count\n}\n```
| 2 | 0 |
['Array', 'JavaScript']
| 0 |
minimum-amount-of-time-to-fill-cups
|
C++ 100% Faster
|
c-100-faster-by-mansimore-9sgj
|
Let\'s take an example \ni/p :\namount = [2,3,9]\nIn this example, instead of calculating all the calculations, I just took the addition of all elements if that
|
mansimore
|
NORMAL
|
2022-07-12T07:12:31.329015+00:00
|
2022-07-12T07:12:31.329061+00:00
| 130 | false |
Let\'s take an example \ni/p :\namount = [2,3,9]\nIn this example, instead of calculating all the calculations, I just took the addition of all elements if that is less than a maximum element of the amount, then return the maximum element of the amount vector.\ni/p :\namount = [8,9,13]\nIn this example, the sum of the first two elements is greater than the maximum element, so I took the addition of all elements, if it is odd then just return (sum / 2) + 1, else return sum/2.\n```\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) \n {\n sort(amount.begin(), amount.end());\n if(amount[0] + amount[1] <= amount[2])\n return amount[2];\n else\n {\n int cnt = amount[0] + amount[1] + amount[2];\n if(cnt % 2 == 1)\n {\n return (cnt/2) + 1;\n }\n else\n {\n return cnt/2;\n }\n }\n }\n};\n```
| 2 | 0 |
['C']
| 0 |
minimum-amount-of-time-to-fill-cups
|
C++ Solution || priority queue || easy-understanding
|
c-solution-priority-queue-easy-understan-4m4h
|
\n\n int fillCups(vector<int>& amount) {\n priority_queue<int> pq; // max heap\n \n for(auto amt: amount)\n pq.push(amt);\n
|
samuraii_Sami
|
NORMAL
|
2022-07-10T18:25:20.498661+00:00
|
2022-07-10T18:25:20.498710+00:00
| 256 | false |
\n```\n int fillCups(vector<int>& amount) {\n priority_queue<int> pq; // max heap\n \n for(auto amt: amount)\n pq.push(amt);\n \n \n int count=0;\n while(!pq.empty())\n {\n if(pq.top()==0) break; // if all bottles are filled\n if(pq.size()==1) // if only one bottle is left , fill it in one by one time, so add the needed time to count\n {\n count+= pq.top();\n break;\n }\n int hot= pq.top(); // maxm cap\n pq.pop();\n int warm = pq.top(); // 2nd max cap\n pq.pop();\n \n \n count++; //pourred both max n 2nd max , so increse counter\n if(hot>1) pq.push(--hot); // if left amt is less then 0 , then we have alreday filled that cup\n if(warm>1)pq.push(--warm); // so wont add to the queue\n \n \n \n \n }\n return count;\n }\n```
| 2 | 0 |
['Heap (Priority Queue)', 'C++']
| 0 |
minimum-amount-of-time-to-fill-cups
|
c++ easy
|
c-easy-by-jarvis_1611-l282
|
\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n /* [5,4,4]\nOutput: 7\n\n 5 4 4\n c w h\n 4 4 3\n 3
|
jarvis_1611
|
NORMAL
|
2022-07-10T06:15:39.949898+00:00
|
2022-07-10T06:15:39.949939+00:00
| 70 | false |
```\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n /* [5,4,4]\nOutput: 7\n\n 5 4 4\n c w h\n 4 4 3\n 3 3 3\n 2 2 3\n 2 1 2\n 1 1 1\n 0 0 1\n 0 0 0 \n pq= 5 4 4\n cnt=1 pq= 4 4 3\n cnt=2 pq= 3 3 3 \n cnt=3 pq 3 2 2 \n cnt=4 pq= 2 2 1\n cnt=5 pq= 1 1 1\n cnt=6 pq= 1 0 0\n cnt=7 pq = 0 0 0\n \n \n */\n\n // we must track of top two frequent nubmers pop them reduce them by one and push them again\n int cnt=0;\n priority_queue<int> pq;\n for(auto i:amount)\n pq.push(i);\n while(pq.top()>0){\n \n int x=pq.top();\n pq.pop();\n int y=pq.top();\n pq.pop();\n cnt++;\n pq.push(x-1);\n pq.push(y-1);\n \n }\n return cnt;\n \n }\n};\n```
| 2 | 0 |
['Heap (Priority Queue)']
| 0 |
minimum-amount-of-time-to-fill-cups
|
C++ | Maxheap | Priority Queue
|
c-maxheap-priority-queue-by-ayushkaushk-4w36
|
\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n priority_queue<int>pq;\n for(auto i:amount)if(i>0)pq.push(i);\n int
|
ayushkaushk
|
NORMAL
|
2022-07-10T05:35:00.878503+00:00
|
2022-07-10T05:35:00.878555+00:00
| 157 | false |
```\nclass Solution {\npublic:\n int fillCups(vector<int>& amount) {\n priority_queue<int>pq;\n for(auto i:amount)if(i>0)pq.push(i);\n int ans=0;\n while(pq.size()>=2)\n {\n int one =pq.top();\n pq.pop();\n int two=pq.top();pq.pop();\n if(one>1)pq.push(one-1);\n if(two>1)pq.push(two-1);\n ans++;\n }\n if(!pq.empty())\n ans+=pq.top();\n return ans;\n }\n};\n```
| 2 | 1 |
['C', 'Heap (Priority Queue)', 'C++']
| 0 |
minimum-amount-of-time-to-fill-cups
|
📌 Python3 solution using sort
|
python3-solution-using-sort-by-dark_wolf-5248
|
\nclass Solution:\n def fillCups(self, a: List[int]) -> int:\n result = 0\n \n\n while sum(a)!=0:\n result+=1\n a
|
dark_wolf_jss
|
NORMAL
|
2022-07-10T04:43:40.190183+00:00
|
2022-07-10T04:43:40.190207+00:00
| 180 | false |
```\nclass Solution:\n def fillCups(self, a: List[int]) -> int:\n result = 0\n \n\n while sum(a)!=0:\n result+=1\n a = sorted(a, reverse=True)\n if a[0] > 0:\n a[0] -= 1\n if a[1] > 0:\n a[1] -=1\n elif a[2] > 0:\n a[2] -= 1\n \n return result\n```
| 2 | 0 |
['Sorting', 'Python3']
| 0 |
minimum-amount-of-time-to-fill-cups
|
Efficient Java Soln (no sort)
|
efficient-java-soln-no-sort-by-lucatian-e7un
|
first while loop:\n\tdetract from max number each pass \nsecond while loop:\n\tfinish remainder if not already finished\n\n\npublic int fillCups(int[] amount) {
|
Lucatian
|
NORMAL
|
2022-07-10T04:36:24.048730+00:00
|
2022-07-10T04:39:30.864176+00:00
| 182 | false |
first while loop:\n\tdetract from max number each pass \nsecond while loop:\n\tfinish remainder if not already finished\n\n```\npublic int fillCups(int[] amount) {\n int count = 0;\n while(amount[0] > 0)\n {\n amount[0] -= 1;\n if(amount[1] < amount[2])\n amount[2] -= 1;\n else\n amount[1] -= 1;\n \n count++;\n }\n while(amount[1] > 0 || amount[2] > 0)\n {\n amount[1] -= 1;\n amount[2] -= 1;\n count++;\n }\n\n return count;\n }\n```\n\n
| 2 | 0 |
['Java']
| 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.