I am learning optimization problem using data structures.
For that I have considered a problem in hand.
I have an array like: movies[] = { 2,3,4,5,6,7,2,4,9 }
I have a sum value: k = 5
Now I am finding the combination of array elements returning the "k"
For example:
2 + 3 = 5
3 + 2 = 5
The code below is able to do that:
#include<iostream>
#include<tuple>
using namespace std;
std::tuple<int, int> movies_combo(int k,int movies[]) {
int value_1 = 0, value_2 = 0;
int size = sizeof(movies);
//First lets sort the array in ascending order
//For optimized solution
double mid = sizeof(movies) / 2;
//Second lets find the sum of combination of array elements which gives "k"
for (int i = 0; i < (size-1); i++) {
for (int j = 0; j < (size - 1); j++) {
if (movies[i] + movies[j] == k) {
cout << "The two movies are: " << movies[i] << "and" << movies[j] << endl;
}
}
}
return make_tuple(value_1, value_2);
}
int main() {
int movies[] = { 2,3,4,5,6,7,2,4,9 };
int k = 6;
int value_1, value_2;
tie(value_1,value_2) = movies_combo(k, movies);
//cout << "The two movies are: " << value_1 << "and" << value_2 << endl;
}
Now I have the time complexity of O(n^2).
I can reduce the complexity further by sorting the array in the beginning and eliminating the values > k. But this is useful only in couple of scenarios and not the general solution of optimization.
I am hoping that there are data structures and algorithmic methods which can be very handy in this case to bring down the complexity of logarithmic level example: nlogn or logn.
If someone has got any idea on reducing the time complexity then let me know.
You can do this in time O(nlogn) and even better O(n) .
O(nlogn) approach:
1 .Sort the elements in time O(nlogn) time.
2 .For each element movies[i]
, apply binary search in array from position i+1
till end of the array to search element k - movies[i]
.
3 .If found, you have your tuple since movies[i] + (k - movies[i]) = k
O(n) approach:
1 .Store all the elements in a hashtable.
2 .For each element movies[i]
, search k - movies[i]
in hashtable, if found you have your tuple.
3 .Since search in hashtable takes O(1) time, this approach takes time O(n) .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.