Google 在线面试真题:Arithmetic Sequence Subarray Sum|谷歌面试真题:等差子数组求和(差值仅为 ±1)

73次阅读
没有评论

An arithmetic sequence is a list of numbers with a definite pattern. If you take any number in the sequence then subtract it from the previous one, the difference is always a constant.

A good arithmetic sequence is an arithmetic sequence with a common difference of either 1 or -1.

For example, [4, 5, 6] is a good arithmetic sequence. So is [6, 5, 4], [10, 9], or [-3, -2, -1]. But, [1, 2, 1] (no common difference) or [3, 7] (common difference is 4) is NOT. Implied, any sequence that has only one element is a good arithmetic sequence.

For example, [4] is a good arithmetic sequence.
Given an integer array nums, return the sum of the sums of each subarray that is a good arithmetic sequence.

Example:

Given nums = [7, 4, 5, 6, 5]. Each of the following subarrays is a good arithmetic sequence:

[7], [4], [5], [6], [5],
[4, 5], [5, 6], [6, 5],
[4, 5, 6]
The sums of these subarrays are:

7, 4, 5, 6, 5,
4 + 5 = 9, 5 + 6 = 11, 6 + 5 = 11,
4 + 5 + 6 = 15
Thus, the answer is the sum of all the sums above, which is:

7 + 4 + 5 + 6 + 5 + 9 + 11 + 11 + 15 = 73
“””

这道谷歌真题要求在数组中找出所有“好等差子数组”:相邻元素差必须是 +1 或 −1,长度为 1 的子数组默认合法。对每个满足条件的子数组先求出元素之和,再把所有这些和累加得到最终答案。实现时需要结合双指针或滑动窗口等思路,高效维护当前连续段的长度与区间和,顺便把所有符合条件的子数组贡献一并算进去。

正文完
 0