[Naive Approach] Using Nested Loop - O(n2) Time and O(1) Space
The main idea of this approach is to iterate over all possible subarrays of the given array using two nested loops. The outer loop selects the starting index of the subarray, while the inner loop extends the subarray to include all possible ending points. During this process, a running sum (temp) is maintained for each subarray and added to the total result.
Output
116
[Expected Approach] Element Contribution Method - O(n) Time and O(1) Space
If we take a close look then we observe a pattern.
Third element arr[2] appears 3 time when subarray start with arr[0]: [1, 4, 5], [1, 4, 5, 3], [1, 4, 5, 3, 2] Third element arr[2] appears 3 time when subarray start with arr[1]: [4, 5], [4, 5, 3], [4, 5, 3, 2] Third element arr[2] appears 3 time when subarray start with arr[2]: [5], [5, 3], [5, 3, 2]
So, We can clearly see that, For any element arr[i] in an array of size n, it appears in exactly (i + 1) * (n - i) subarrays.