Find the longest sequence length whose sum is divisible by 3

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

    You apply dynamic programming. For every position you compute 3 values:

    • The longest sequence ending in that position which has sum s = 0 mod 3
    • The longest sequence ending in that position which has sum s = 1 mod 3
    • The longest sequence ending in that position which has sum s = 2 mod 3

    So given this value for position i you can easily compute the new ones for position i+1.

提交回复
热议问题