Skip to content
This repository has been archived by the owner on Oct 7, 2023. It is now read-only.

Created .py code to find the longest subarray with sum divisible by K #1503

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions AMjcSK/Ul9oRr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
def LongestSubarrayWithSumDivisibleByK(nums, k):

prefix_sum = 0
remainder_index_map = {}
max_length = 0

for i, num in enumerate(nums):
prefix_sum += num
remainder = prefix_sum % k

if remainder < 0:
remainder += k

if remainder == 0:
max_length = i + 1
elif remainder in remainder_index_map:
max_length = max(max_length, i - remainder_index_map[remainder])

if remainder not in remainder_index_map:
remainder_index_map[remainder] = i

return max_length

nums = list(map(int, input("Enter a list of integers separated by spaces: ").split()))

k = int(input("Enter the value of k: "))

result = LongestSubarrayWithSumDivisibleByK(nums, k)
print("The longest subarray with sum divisible by K is of length:", result)