[ad_1]
Given an array arr[] of N integers, the duty is to divide discover all of the indices such that prefix sum (i.e. sum of components in vary [0, i)) is greater than the suffix sum (elements in the range [i, N-1])
Examples:
Enter: arr = [10, -3, 4, 6]
Output: [1, 3]
Rationalization: Take into account index 1. Prefix sum = 10, suffix sum = 7, i.e. (10 > 7)
Take into account index 3. Prefix sum = 11, suffix sum = 6, i.e(11 > 6)Enter: arr = [-2, -3, -4, 10]
Output: []
Rationalization: There isn’t any index such that prefix sum is bigger than suffix sum.
Method: The fundamental thought is to contemplate every index and calculate the prefix and suffix sum for that. If the prefix sum is bigger than the suffix sum, then insert this index into the reply.
Under is the implementation of the above strategy.
Python3
|
Time Complexity: O(N2)
Auxiliary House: O(1)
Environment friendly Method: The above strategy could be optimized additional by calculating the sum of the array primarily based on the next thought:
Sum of array = prefix sum at index i + suffix sum at index i. So discover the array sum. Then iterate array and carry on calculating the prefix sum. If the situation of the issue is happy by prefix and suffix sum then that index can be a part of reply.
Observe the steps talked about beneath to resolve the issue:
- Iterate the array and fins the sum of the array (say sum).
- Initialize variable (say temp) to retailer prefix sum.
- Iterate from i = 1 to N-1:
- Add arr[i-1] to prefix sum.
- Calculate suffix sum utilizing the above commentary.
- If the prefix and suffix sum fulfill the situation of the issue, i can be one of many solutions.
- Return the array storing the legitimate indices.
Under is the implementation of the above strategy.
Python3
|
Time Complexity: O(N)
Auxiliary House: O(1)
[ad_2]