Program to find the maximum sum of the subarray modulo by m in Python

PythonServer Side ProgrammingProgramming

Program to find the maximum sum of the subarray modulo by m in Python

Suppose we have an array nums with n elements. We have another integer m. We have to find the maximum value of sum of any of its subarrays modulo m.

So, if the input is like nums = [1,5,7,3] m = 5, then the output will be 3 because

  • [1] mod 5 = 1
  • [5] mod 5 = 0
  • [7] mod 5 = 2
  • [3] mod 5 = 3
  • [1,5] mod 5 = 1
  • [5,7] mod 5 = 2
  • [7,3] mod 5 = 0
  • [1,5,7] mod 5 = 3
  • [5,7,3] mod 5 = 0
  • [1,5,7,3] mod 5 = 1

To solve this, we will follow these steps −

  • csum := a list and initially insert nums[0] mod m into it
  • for each x in nums except first value, do
    • insert (last item of csum + x) mod m at the end of csum
  • seen := a list with single element initially that is 0
  • max_sum := -1
  • for each s in csum, do
    • idx := the left most position to insert s into seen so that the list will be sorted
    • if idx < size of seen, then
      • max_sum := maximum of max_sum and s
    • otherwise,
      • insert s at the left most index of seen so that array is sorted
    • insert s at the left most index of seen so that array is sorted
  • return max_sum

Example

Let us see the following implementation to get better understanding −

import bisect
def solve(nums, m):
   csum = [nums[0] % m]
   for x in nums[1:]:
      csum.append((csum[-1] + x) % m)

   seen = [0]
   max_sum = -1
   for s in csum:
      idx = bisect.bisect_left(seen, s)
      if idx < len(seen):
         max_sum = max(max_sum, s, (s - seen[idx]) % m)
      else:
         max_sum = max(max_sum, s)
      bisect.insort_left(seen, s)

   return max_sum

nums = [1,5,7,3]
m = 5
print(solve(nums, m))

Input

"pptpp", [(1,1),(1,4),(1,1),(0,2)]

Output

3
raja
Updated on 11-Oct-2021 06:35:17

Advertisements