Find the longest sequence length whose sum is divisible by 3

前端 未结 4 1261
北荒
北荒 2020-12-15 21:03

I have an exercise that needs to be done with O(n) time complexity, however, I can only solve it with an O(n^2) solution.

You have an array and you need to count the

4条回答
  •  一向
    一向 (楼主)
    2020-12-15 21:16

    Let's take a look at prefix sums. A [L, R] subarray is divisble by 3 if and only if
    prefixSum[L - 1] mod 3 = prefixSum[R] mod 3. This observation gives a very simple linear solution(because there are only 3 possible values of a prefix sum mod 3, we can simply find the first and the last one).

    For example, if the input array is {1, 2, 3, -4, -1}, the prefix sums are {0, 1, 0, 0, 2, 1}. (there are n + 1 prefix sums because of an empty prefix). Now you can just take a look at the first and last occurrence of 0, 1 and 2.

提交回复
热议问题