【算法心得】Integer is also a constraint

https://leetcode.com/problems/arithmetic-subarrays/description/?envType=daily-question&envId=2023-11-23

First time I see this question, it is a Range Query, so I think it meight be Segment Tree, but in this question, there is an operation of rearrange, for example. 5 9 3 7 is arithmetic sequence, but its subarray 5 9 3 is not. Segment Tree failed

nums length is 1e5, query count is 500, in naive algorithm, even if each query takes O(n), total is 1e7, it is not enough

(I’m blind. nums[i]'s value is in 1e5, nums.length is only 500)

So it is necessary to preprocessing the nums to make each query faster. If there is an arithmetic sequence and we want to spread it, the new number is either maxnum+diff or minnum-diff. According to this feature, we can control the preprocessing time conplexity to O(n):

  1. find a consequent 3 integer which is arithmetic.
  2. check the new number
    • neither maxnum+diff nor minnum-diff: use current i-2 as new 3-element arithmetic sequence and spread
    • otherwise add the new number to current arithmetic sequence

Just then I realized this algorithm have a huge loophole, arithmetic sequence can not only derived from a shorter arithmetic sequence (such as “1 7 5 3”). So we must find a new constrait to “pruning”

https://leetcode.com/problems/arithmetic-subarrays/solutions/4318924/beats-100-explained-with-video-simple-maths-solution-visualized-too/?envType=daily-question&envId=2023-11-23

In this solution, the author mentioned that, in an arithmetic sequence, (maxnum - minnum) % (len - 1) == 0, query which does not meet this condition can return false directly.

And for query meet this condition, we dont need to sort, too. We have found the minnum of these subarray, so we can calculate if it is arithmetic array, each item located in which index, if the index repeated, return false.
else return true.

你可能感兴趣的:(算法,算法)