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.
My Java 8 solution, passing all test-cases, for Max Score of 60
The idea is to do a "continuous trailing prefix modulo sum" as we iterate through the array, while comparing that with the maxModSum that we have seen so far & updating that as required. We maintain a prefixSumTreeSet to keep track of all the distinct prefixSums we have seen so far. We check if we have encountered a prefixSum that's higher than the curPrefixSum, and if so: then we use the higherPrefixTS value to update maxModSum as required.
By using this approach, we only need to loop through the array once from start to finish (costing O(n) time). In each iteration, we spend some time going through the prefixSumTreeSet to locate the "higher" element, or to add a new element to the TreeSet (costing O(log(n)) time. This results in an overall Time Complexity of O(n * log(n)).
Maximum Subarray Sum
You are viewing a single comment's thread. Return to all comments →
My Java 8 solution, passing all test-cases, for Max Score of 60
The idea is to do a "continuous trailing prefix modulo sum" as we iterate through the array, while comparing that with the
maxModSum
that we have seen so far & updating that as required. We maintain aprefixSumTreeSet
to keep track of all the distinct prefixSums we have seen so far. We check if we have encountered a prefixSum that's higher than thecurPrefixSum
, and if so: then we use thehigherPrefixTS
value to updatemaxModSum
as required.By using this approach, we only need to loop through the array once from start to finish (costing
O(n)
time). In each iteration, we spend some time going through theprefixSumTreeSet
to locate the "higher" element, or to add a new element to the TreeSet (costingO(log(n))
time. This results in an overall Time Complexity ofO(n * log(n))
.