Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find number of sublists containing maximum and minimum after deleting only one element in Python
Given a list of numbers, we can delete at most one element to maximize the number of sublists containing both the maximum and minimum values of the resulting list. This problem requires analyzing different scenarios when removing elements.
Problem Understanding
For the input nums = [3, 2, 6, 2, 4, 10], if we remove 10, we get [3, 2, 6, 2, 4] where min=2 and max=6. There are 8 sublists containing both values ?
[2, 6] at indices (1,2)
[6, 2] at indices (2,3)
[2, 6, 2] at indices (1,3)
[3, 2, 6] at indices (0,2)
[6, 2, 4] at indices (2,4)
[2, 6, 2, 4] at indices (1,4)
[3, 2, 6, 2] at indices (0,3)
[3, 2, 6, 2, 4] at indices (0,4)
Algorithm
The solution uses a helper function to count valid sublists and tests removing minimum or maximum elements if they appear only once ?
class Solution:
def solve(self, nums):
if len(nums) <= 1:
return len(nums)
def check(lst):
mn, mx = min(lst), max(lst)
min_pos, max_pos = None, None
ret = 0
for i, num in enumerate(lst):
if num == mn:
min_pos = i
if num == mx:
max_pos = i
if min_pos is None or max_pos is None:
continue
ret += min(min_pos, max_pos) + 1
return ret
ret = check(nums)
for rem_cand in [min(nums), max(nums)]:
if nums.count(rem_cand) == 1:
idx = nums.index(rem_cand)
ret = max(ret, check(nums[:idx] + nums[idx + 1:]))
return ret
# Test the solution
ob = Solution()
nums = [3, 2, 6, 2, 4, 10]
print(ob.solve(nums))
8
How It Works
The check() function counts sublists containing both min and max values. For each position, if we've seen both min and max elements, we can form sublists starting from position 0 up to the leftmost of the current min/max positions.
The main algorithm tries three scenarios ?
Keep the original list
Remove the minimum element (if it appears only once)
Remove the maximum element (if it appears only once)
Example Walkthrough
# Example with step-by-step analysis
nums = [3, 2, 6, 2, 4, 10]
# Original list: min=2, max=10
# After removing max(10): [3, 2, 6, 2, 4] with min=2, max=6
# This gives the maximum count of 8 sublists
ob = Solution()
result = ob.solve(nums)
print(f"Maximum sublists: {result}")
# Test with another example
nums2 = [1, 2, 3]
result2 = ob.solve(nums2)
print(f"For {nums2}: {result2}")
Maximum sublists: 8 For [1, 2, 3]: 3
Conclusion
This algorithm efficiently finds the maximum number of sublists by testing removal of unique minimum or maximum elements. The key insight is that removing extreme values can create more balanced min-max distributions, leading to more valid sublists.
