+ 1

What is faster way to compute maximum difference in a vector?

Hi Suppose we have a vector as below which is not in ascending order. vector<int> vecInput = {1,9,-2,5,20,3,4,11}; Now assume that task is to find out MAXIMUM absolute difference between vector elements. here in case, expected output is 20-(-2) = 22. It's always not a good way to loop through all elements and compare with remaining elements to come up with output. This requires two for loop. One way is to sort vector, find size of vector and get difference between last element value with first value. Another way is to find max_element and min_element. Substract these values to find output. Which is best option to come up with solution considering performance aspects?

7th Jul 2018, 4:27 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
8 Respostas
+ 1
Finding max and min in array is to compare all values with previously stored max and min.. Correct? One need to use two if conditions also in a loop... right?
7th Jul 2018, 5:10 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
The second one. Finding max and min are done in linear time and best sorting algorithm is done in logarithmic time.
7th Jul 2018, 5:52 AM
Дмитро Іванов
Дмитро Іванов - avatar
+ 1
It's bad thing I guess as we are looping also with two if conditions
7th Jul 2018, 12:13 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Correct...max and min might be linear, but it's done twice one for each.. where as sorting is done once only... still second one is best one?
7th Jul 2018, 12:16 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Any good sites for performance related articles ??
7th Jul 2018, 3:21 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Ketan Lalcheta, I would suggest to take an online course on algorithms. For beginners, I world recommend Algorithms specialization from Stanford at Coursera: https://www.coursera.org/specializations/algorithms But there are many online courses on this subject, so you can choose.
9th Jul 2018, 6:24 AM
Viacheslav
0
Ketan Lalcheta of course 2N is better, then logN.
7th Jul 2018, 12:17 PM
Дмитро Іванов
Дмитро Іванов - avatar
0
Finding min and max is better in general case. Sorting requires O(n log n) operations. Even in special cases when you can use O(n) sorting algorithm like radix sort, constant in min-max algorithm will be usually less. The only exception is already sorted input array, but this is not your case.
7th Jul 2018, 2:30 PM
Viacheslav