Maximum difference between two elements such that larger element appears after the smaller number.
Examples :
Input : arr = {2, 3, 10, 6, 4, 8, 1} Output : 8 Explanation : The maximum difference is between 10 and 2. Input : arr = {7, 9, 5, 6, 3, 2} Output : 2 Explanation : The maximum difference is between 9 and 7.
That’ll fail with any array in which the max difference isn’t between the max number and the min number before it, e.g. just changing one number from the second example to arr = []int{7, 9, 1, 6, 3, 2} (it should return 5, but it’ll return 2 instead).
Anyway, I think the idea in these cases is to help the poster solve their problem by looking at what they’ve done and pointing out any mistakes or guide them towards the solution, rather than just throw some code that solves it.
That’s right: the maximum difference is 5, where the larger element is 6 and the smaller number is 1. Notice how it says larger and smaller, not largest nor smallest (i.e., it’s relative, not absolute). If it said largest, then yeah, 9 is the largest element and the max difference would be 2, but it doesn’t say that. The only condition is that the bigger number between the 2 from which you are taking the difference comes after the smaller one, i.e., arr = []int{7, 9, 1, 3, 2, 6} should return 5 too, while []int{7, 9, 6, 3, 2, 1} should return 2.