diff --git a/Greedy/HighestProduct.cpp b/Greedy/HighestProduct.cpp index 0d33dd0..f5e391b 100644 --- a/Greedy/HighestProduct.cpp +++ b/Greedy/HighestProduct.cpp @@ -1,85 +1,15 @@ -// https://www.interviewbit.com/problems/highest-product/ - int Solution::maxp3(vector &A) { - // Do not write main() function. - // Do not read input, instead use the arguments to the function. - // Do not print the output, instead return values as specified - // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details - - if(A.size() < 3){ - return 0; - } - - long long int neg1 = INT_MAX, neg2 = INT_MAX; - int neg1_count = 0; - - for(int i = 0; i < A.size(); i++){ - if(A[i] < neg1 && A[i] < 0){ - neg1_count = 1; - neg1 = A[i]; - } - else if(A[i] == neg1 && A[i] < 0){ - neg1_count++; - } - } - - if(neg1_count > 1){ - neg2 = neg1; - } - else if(neg1_count == 1){ - for(int i = 0; i < A.size(); i++){ - if(A[i] < 0 && A[i] < neg2 && neg1 < A[i]){ - neg2 = A[i]; - } - } - } - - long long int max1 = INT_MIN, max2 = INT_MIN, max3 = INT_MIN; - int max1_count = 0, max2_count = 0; - - for(int i = 0; i < A.size(); i++){ - if(A[i] > max1){ - max1 = A[i]; - max1_count = 1; - } - else if(A[i] == max1){ - max1_count++; - } - } - - if(max1_count > 1){ - max1_count--; - max2 = max1; - } - else{ - for(int i = 0; i < A.size(); i++){ - if(A[i] > max2 && max1 > A[i]){ - max2 = A[i]; - max2_count = 1; - } - else if(A[i] == max2 && max1 > A[i]){ - max2_count++; - } - } - } - - if(max1_count > 1){ - max3 = max1; - } - else if(max2_count > 1){ - max3 = max2; - } - else{ - for(int i = 0; i < A.size(); i++){ - if(A[i] > max3 && max2 > A[i] && max1 > A[i]){ - max3 = A[i]; - } - } - } - - if(neg1 == INT_MIN || neg2 == INT_MIN){ - return (int)max1*max2*max3; - } - - return (int)max(max1*max2*max3, max1*neg1*neg2); + + sort(A.begin(), A.end()); //sort all numbers + + int n = A.size(); + // Now as last three number are greater among all and if all the three last numbers are positive and negative then max pdt will all_pos.If only 2 elements in the array are positive + // then the pdt of three number (i.e.maximum) is negative which means maximum comes in this case is also from all_pos + int all_pos = A[n-3]*A[n-2]*A[n-1]; + // One case in which there is only one positive number in this case can take two negative numbers which on multipling becomes positive so for that we pick those number from A[0] & A[1] + // becoz A[0] and A[1] are minimum and negative multipling gives biggest. + int pos_neg = A[0]*A[1]*A[n-1]; + + return max(all_pos, pos_neg); // maximum of all_pos & pos_neg + } diff --git a/Two-Pointers/MaxContiguousSeriesOf1s.cpp b/Two-Pointers/MaxContiguousSeriesOf1s.cpp index f676279..7bd93a8 100644 --- a/Two-Pointers/MaxContiguousSeriesOf1s.cpp +++ b/Two-Pointers/MaxContiguousSeriesOf1s.cpp @@ -58,7 +58,7 @@ vector Solution::maxone(vector &A, int B) { } } } - + vector sol; if(ov_count != 0){ for(int t = ov_st; t <= ov_end; t++){ sol.push_back(t);