VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximize-number-of-indices-with-prefix-sum-equal-to-0/

⇱ Maximize number of indices with prefix sum equal to 0 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximize number of indices with prefix sum equal to 0

Last Updated : 10 Apr, 2024

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:

  • Maintain a map, say freqMap to store the frequency of prefix sums for every segment.
  • Also, maintain a variable maxFreq to store the frequency of the most frequent prefix sum.
  • Iterate over the array arr[], and check,
    • If arr[i] = 0, if this is the first occurrence of 0, simply add freqMap[0] to the answer otherwise add maxFreq to the answer. Also, clear the freqMap and reset maxFreq to 0.
    • If arr[i] != 0, add the current element to the prefix sum. Increment the frequency of new prefix sum by 1 and update maxFreq if the new prefix sum becomes the most frequent prefix sum.
  • After iterating over the entire array, return the final answer.

Below is the implementation of the algorithm:


Output
3

Time Complexity: O(N*logN), where N is the size of the input array arr[].
Auxiliary Space: O(N)

Comment