Find the longest sequence length whose sum is divisible by 3

前端 未结 4 1260
北荒
北荒 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:07

    Iterate through the array, summing the total as you go. Record the position of the first position where the modulo sum is 0. Also, record the position of he first position where the modulo sum is 1. And, finally, record the position of he first position where the modulo sum is 2.

    Do the same thing backwards also, recording the last position where the modulo sum is 0, 1, and 2. That gives three possibilities for the longest sequence - you just check which pair are farthest apart.

提交回复
热议问题