We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Finally, got the right approach for optimization and solved it.
This was one of the best problems I've come accross on HR so far, in terms of combining mathematical and programming skills, which did not require knowledge of a certain mathematical approach like game theory, graph theory etc, or it may be the case that I just re-invented them.
Track the totals and product totals of certain indices (Please see item 3, we start tracking a new range only where the sign of two adjacent elements are different) of the array in two new arrays
Keep a set for active ranges that we are interested in
We don't have to start tracking a range for all the indices. If a[i] > 0 and a[i+1] > 0, the range starting from i will always have a greater product then the range starting at i+1
3.a This can also be prooved mathematically using just basic algebra
Whenever the total of the range starting from a certain index changes sign, we can stop tracking it
4.a And this is because if the total of the sub-segment becomes ZERO at any point, any product calculations that will include this one on the left will be less than if they don't have it.
4.b This can be prooved mathematically, easily, again.
The core of the optimization is to stop tracking ranges that;
5.a started from an element having the same sign (+ or -)
5.b is starting in the array later than some other range
5.c and whose current product is LESS than the current product of the other range at offset i
5.d This is because they have the same sign and if the later range has a smaller product at i, it will never have a greater product at any offset i compared to a range that started earlier.
With all this, and with 70 lines of code, voila, I got full score.
Very well problem definition and let me tell you, ChatGPT will never get you under O(n^2) :)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Pair Sums
You are viewing a single comment's thread. Return to all comments →
Finally, got the right approach for optimization and solved it.
This was one of the best problems I've come accross on HR so far, in terms of combining mathematical and programming skills, which did not require knowledge of a certain mathematical approach like game theory, graph theory etc, or it may be the case that I just re-invented them.
With all this, and with 70 lines of code, voila, I got full score.
Very well problem definition and let me tell you, ChatGPT will never get you under O(n^2) :)