File tree 1 file changed +26
-14
lines changed
scripts/algorithms/O/Optimal Division
1 file changed +26
-14
lines changed Original file line number Diff line number Diff line change 1
- // Runtime: 4 ms (Top 45.16%) | Memory: 8 MB (Top 87.37%)
1
+ // Runtime: 0 ms (Top 100.0%) | Memory: 8.50 MB (Top 25.14%)
2
+
3
+ // This code is using 2nd Approach.
4
+
2
5
class Solution {
3
6
public:
4
7
string optimalDivision (vector<int >& nums) {
5
- string s=" " ;
6
- if (nums.size ()==1 )
7
- return to_string (nums[0 ]);
8
- if (nums.size ()==2 )
9
- return to_string (nums[0 ])+' /' +to_string (nums[1 ]);
10
- for (int i=0 ;i<nums.size ();i++)
11
- {
12
- s+=to_string (nums[i])+" /" ;
13
- if (i==0 )
14
- s+=" (" ;
8
+ int n=nums.size ();
9
+ string ans;
10
+
11
+ // check for size if its 1 then we can't use parantheses and
12
+ // if its 2 then also we should not use it.
13
+
14
+ if (n==1 ) return ans=to_string (nums[0 ]);
15
+ if (n==2 ) return ans=to_string (nums[0 ])+" /" +to_string (nums[1 ]);
16
+
17
+ // for size greater than 2 add paranthese after first number
18
+
19
+ ans=to_string (nums[0 ]);
20
+ ans.append (" /(" );
21
+ for (int i=1 ;i<n-1 ;i++){
22
+ ans.append (to_string (nums[i])+" /" );
15
23
}
16
- s[s.size ()-1 ]=' )' ;
17
- return s;
24
+ ans.append (to_string (nums[n-1 ]));
25
+ ans.append (" )" );
26
+
27
+ // finally this becomes as a/(b/c/d/....) which is our answer
28
+
29
+ return ans;
18
30
}
19
- };
31
+ };
You can’t perform that action at this time.
0 commit comments