![]() |
VOOZH | about |
Given an array arr[] of size N, you can perform the following operation on the array any number of times: If arr[i]=0, we can replace it with any integer. Your task is to maximize the number of indices having prefix sum = 0.
Examples:
Input: N = 7, arr[] = {1, -1, 0, 2, 4, 2, 0, 1}
Output: 3
Explanation: We can have at max 3 indices with prefix sum = 0 by changing arr[6] to -8. So, arr[] will become {1, -1, 0, 2, 4, 2, -8, 1}. Now, the prefix sum array would be {1, 0, 0, 2, 6, 8, 0, 1}Input: N = 3, arr[] = {1000, 1000, 0}
Output: 1
Explanation: We can have at max 1 index with prefix sum = 0 by changing arr[2] to -2000. So, arr[] will become {1000, 1000, -2000}. Now, the prefix sum array would be {1000, 1000, 0}.
Approach: To solve the problem, follow the below idea:
Let's consider that the indices where arr[i] = 0 are: z1, z2, z3 .... zx, so we can divide the array arr[] into sub-segments like: [0...z1-1], [z1+1...z2-1], [z2+1...z3-1], and so on. After dividing it into sub-segments,
- For the first segment [0...z1-1], no change can be made to all the prefix sums from [0...z1-1] as we cannot change any element before index z1. So, for segment arr[0...z1-1], we can find the number of indices with prefix sum = 0 by iterating from 0 to z1 and maintaining the frequency of 0 prefix sums for each index.
- Now for all the remaining segments, we can turn the most frequent prefix sum in that segment, say P to 0 by changing the 0 which is just before the segment to -P. So, we can find the number of indices with prefix sum = 0 by maintaining the frequency of prefix sum in that segment and adding it to the answer.
Step-by-step algorithm:
Below is the implementation of the algorithm:
3
Time Complexity: O(N*logN), where N is the size of the input array arr[].
Auxiliary Space: O(N)