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 Out the Largest K-Divisible Subsequence Sum in Python
Given a list of non-negative numbers and a positive value k, we need to find the maximum sum of a subsequence such that the sum is divisible by k. A subsequence can be formed by removing some elements from the original array while maintaining the relative order.
Problem Understanding
For example, if we have nums = [4, 6, 8, 2] and k = 2, the sum of all elements is 20, which is divisible by 2. So the answer is 20.
Approach
The algorithm works as follows:
- Calculate the total sum of all numbers
- If the total sum is already divisible by k, return it
- Otherwise, find the smallest subsequence whose sum has the same remainder as the total sum when divided by k
- Remove this subsequence sum from the total to get the maximum k-divisible sum
Implementation
from itertools import chain, combinations
class Solution:
def solve(self, nums, k):
nums_sum = sum(nums)
remainder = nums_sum % k
# If total sum is already divisible by k
if remainder == 0:
return nums_sum
# Sort to try smaller combinations first
nums.sort()
# Generate all possible subsequences
for tpl in chain.from_iterable(combinations(nums, r) for r in range(1, len(nums) + 1)):
subseq_sum = sum(tpl)
# If this subsequence has same remainder, remove it
if subseq_sum % k == remainder:
return nums_sum - subseq_sum
return 0
# Test the solution
solution = Solution()
result = solution.solve([4, 6, 8, 2], 2)
print(f"Maximum k-divisible subsequence sum: {result}")
Maximum k-divisible subsequence sum: 20
Example with Different Input
Let's test with another example where the total sum is not divisible by k:
solution = Solution()
# Test case where we need to remove elements
nums = [3, 1, 4, 2]
k = 3
result = solution.solve(nums, k)
print(f"Input: {nums}, k = {k}")
print(f"Total sum: {sum(nums)}")
print(f"Maximum k-divisible subsequence sum: {result}")
Input: [3, 1, 4, 2], k = 3 Total sum: 10 Maximum k-divisible subsequence sum: 9
How It Works
In the second example:
- Total sum = 10, remainder = 10 % 3 = 1
- We need to find the smallest subsequence with remainder 1
- The element [1] has sum 1, and 1 % 3 = 1
- So we remove 1 from the total: 10 - 1 = 9, which is divisible by 3
Time Complexity
The time complexity is O(2^n × n) where n is the length of the input array, as we generate all possible subsequences and calculate their sums. The space complexity is O(n) for storing combinations.
Conclusion
This solution finds the largest k-divisible subsequence sum by removing the smallest subsequence that has the same remainder as the total sum. While the approach works correctly, it has exponential time complexity and may not be efficient for large inputs.
