【算法心得】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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值