Given an integer array `nums`, an element at index `i` is considered *dominant* if it is strictly greater than the sum of all elements to its left (from index `0` to `i-1`) and strictly greater than the sum of all elements to its right (from index `i+1` to `nums.length-1`). Note that the sum of elements over an empty range is considered to be `0`. Find all dominant elements in the array. If there are multiple dominant elements, return the 0-based index of the dominant element that has the maximum value. If there is a tie in the maximum value, return the smallest index among them. If no dominant element exists, return `-1`.
Explanation: Let's check each element: - Index 0 (value 1): Left sum = 0, Right sum = 17. 1 is not greater than 17. - Index 1 (value 2): Left sum = 1, Right sum = 15. 2 is not greater than 15. - Index 2 (value 8): Left sum = 3, Right sum = 7. Since 8 > 3 and 8 > 7, this element is dominant. - Index 3 (value 3): Left sum = 11, Right sum = 4. 3 is not greater than 11. - Index 4 (value 4): Left sum = 14, Right sum = 0. 4 is not greater than 14. Only the element at index 2 is dominant, so we return 2.
Explanation: Let's check each element: - Index 0 (value 5): Left sum = 0, Right sum = -5. 5 > 0 and 5 > -5 (dominant). - Index 1 (value -10): Left sum = 5, Right sum = 5. -10 is not dominant. - Index 2 (value 5): Left sum = -5, Right sum = 0. 5 > -5 and 5 > 0 (dominant). Both index 0 and index 2 are dominant. Since they both have the same maximum value of 5, we return the smaller index, which is 0.
Explanation: No element is strictly greater than both its left sum and right sum. For example, at index 1, the value 2 is not strictly greater than the left sum of 2. Thus, we return -1.
Iterating arrays and tracking min/max
No dry run loaded.
🚀 Practice this problem
Run code, get AI hints & track streak