Program to find number of sublists we can partition so given list is sorted finally in python


Suppose we have a list of numbers called nums. We can partition the list into some individual sublists then sort each piece. We have to find the maximum number of sublists we can partition to such that nums as a whole is sorted afterwards.

So, if the input is like nums = [4, 3, 2, 1, 7, 5], then the output will be 2, as we can sort the sublists like [4, 3, 2, 1] and [7, 5]

To solve this, we will follow these steps:

  • count := 0
  • main_sum := 0, sorted_sum := 0
  • for each element x from nums and y from sorted form of nums, do
    • main_sum := main_sum + x
    • sorted_sum := sorted_sum + y
    • if main_sum is same as sorted_sum, then
      • count := count + 1
  • return count

Let us see the following implementation to get better understanding:

Example

Live Demo

class Solution:
   def solve(self, nums):
      count = 0
      main_sum = sorted_sum = 0

      for x, y in zip(nums, sorted(nums)):
         main_sum += x
         sorted_sum += y
         if main_sum == sorted_sum:
            count += 1

      return count

ob = Solution()
nums = [4, 3, 2, 1, 7, 5]
print(ob.solve(nums))

Input

[4, 3, 2, 1, 7, 5]

Output

2

Updated on: 26-Nov-2020

100 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements