Thanks for the solution but please try to explain program with the example. I have not understood program, so now I will write program and will try to understand it
class Solution { public: int closestToZero(int arr[], int n) { sort (arr, arr + n); // sorting the array int i = 0, j = n - 1; int sum = arr[i] + arr[j]; // initializing sum int diff = abs (sum); // initializing the result while (i < j) { // if we have zero sum, there's no result better. Hence, we return if (arr[i] + arr[j] == 0) return 0; // if we get a better result, we update the difference if (abs (arr[i] + arr[j]) < abs (diff)) { diff = (arr[i] + arr[j]); sum = arr[i] + arr[j]; } else if(abs (arr[i] + arr[j]) == abs (diff)) { sum=max(sum,arr[i]+arr[j]); } // if the current sum is greater than zero, we search for a smaller sum if (arr[i] + arr[j] > 0) j--; // else, we search for a larger sum else i++; } return sum; } };
The correct and optimal method starts at 8:06, for those who are short of time
Thanks for the solution but please try to explain program with the example. I have not understood program, so now I will write program and will try to understand it
You're welcome, Sanjay. We'll try to incorporate your input in our future videos.
👍
class Solution
{
public:
int closestToZero(int arr[], int n)
{
sort (arr, arr + n); // sorting the array
int i = 0, j = n - 1;
int sum = arr[i] + arr[j]; // initializing sum
int diff = abs (sum); // initializing the result
while (i < j)
{
// if we have zero sum, there's no result better. Hence, we return
if (arr[i] + arr[j] == 0)
return 0;
// if we get a better result, we update the difference
if (abs (arr[i] + arr[j]) < abs (diff))
{
diff = (arr[i] + arr[j]);
sum = arr[i] + arr[j];
}
else if(abs (arr[i] + arr[j]) == abs (diff))
{
sum=max(sum,arr[i]+arr[j]);
}
// if the current sum is greater than zero, we search for a smaller sum
if (arr[i] + arr[j] > 0)
j--;
// else, we search for a larger sum
else
i++;
}
return sum;
}
};
if sum is minimum then also we need to check l++ and r--, to compare with other min
thx. isn't safe to start the l index with 1 since min_sum was already evaluated using [0] and [1] indices before the loop began.
But if quick sort takes O(n^2) in worst case, how can we assume this as an optimal solution? Merge Sort is my choice
sir can you please explain this with program ..thank you for your solution
-10 + (-80) = -90.
Is it less close to zero than +5.
I presume I did not understand the meaning of closest to zero
take absolute value. absolute value is making every non negative number to positive, if you take abs value of -90, it becomes +90.
Please make video with Java and Kotlin
Thanks for sharing this as other videos! You are awesome guys!
Thanks reyou7 for the appreciation!
What if i want those two elements whose sum is equal to 0
yes it can be found...
how is it that O(nlogn) + O(n) = O(nlogn)?
Please Study space and time Complexity