We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
importbisectdefmaximumSum(a,m):# List to store prefix sums in sorted orderprefix_sums=[]# Current prefix sum modulo m and maximum sum foundprefix_sum=0max_sum=0fornumina:# Update prefix sum and take modulo mprefix_sum=(prefix_sum+num)%m# Update max_sum with the current prefix_sum if it's largermax_sum=max(max_sum,prefix_sum)# Find the insertion point to keep prefix_sums sortedidx=bisect.bisect_right(prefix_sums,prefix_sum)# If there's a larger prefix_sum, update max_sum considering wrap-aroundifidx<len(prefix_sums):max_sum=max(max_sum,(prefix_sum-prefix_sums[idx]+m)%m)# Insert current prefix_sum into the sorted listbisect.insort(prefix_sums,prefix_sum)returnmax_sum
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Maximum Subarray Sum
You are viewing a single comment's thread. Return to all comments →