Weighted Prefix Search
Given n strings and a weight associated with each string. The task is to find the maximum weight of string having the given prefix. Print “-1” if no string is present with given prefix.
Input : s1 = "geeks", w1 = 15 s2 = "geeksfor", w2 = 30 s3 = "geeksforgeeks", w3 = 45 prefix = geek Output : 45 All the string contain the given prefix, but maximum weight of string is 45 among all.
Method 1: (Brute Force)
Check all the string for given prefix, if string contains the prefix, compare its weight with maximum value so far.
Below is the implementation of above idea :
Method 2 (efficient):
The idea is to create and maintain a Trie. Instead of the normal Trie where we store the character, store a number with it, which is maximum value of its prefix. When we encounter the prefix again update the value with maximum of existing and new one.
Now, search prefix for maximum value, run through the characters starting from the root, if one of character is missing return -1, else return the number stored in the root.
Below is the implementation of the above idea :
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.