|
| 1 | +/** |
| 2 | + * 1630. Arithmetic Subarrays |
| 3 | + * https://leetcode.com/problems/arithmetic-subarrays/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * A sequence of numbers is called arithmetic if it consists of at least two elements, and the |
| 7 | + * difference between every two consecutive elements is the same. More formally, a sequence s |
| 8 | + * is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i. |
| 9 | + * |
| 10 | + * For example, these are arithmetic sequences: |
| 11 | + * - 1, 3, 5, 7, 9 |
| 12 | + * - 7, 7, 7, 7 |
| 13 | + * - 3, -1, -5, -9 |
| 14 | + * |
| 15 | + * The following sequence is not arithmetic: |
| 16 | + * - 1, 1, 2, 5, 7 |
| 17 | + * |
| 18 | + * You are given an array of n integers, nums, and two arrays of m integers each, l and r, |
| 19 | + * representing the m range queries, where the ith query is the range [l[i], r[i]]. All the |
| 20 | + * arrays are 0-indexed. |
| 21 | + * |
| 22 | + * Return a list of boolean elements answer, where answer[i] is true if the subarray |
| 23 | + * nums[l[i]], nums[l[i]+1], ... , nums[r[i]] can be rearranged to form an arithmetic |
| 24 | + * sequence, and false otherwise. |
| 25 | + */ |
| 26 | + |
| 27 | +/** |
| 28 | + * @param {number[]} nums |
| 29 | + * @param {number[]} l |
| 30 | + * @param {number[]} r |
| 31 | + * @return {boolean[]} |
| 32 | + */ |
| 33 | +var checkArithmeticSubarrays = function(nums, l, r) { |
| 34 | + return l.map((start, index) => { |
| 35 | + const end = r[index]; |
| 36 | + const subarray = nums.slice(start, end + 1); |
| 37 | + return isArithmetic(subarray); |
| 38 | + }); |
| 39 | + |
| 40 | + function isArithmetic(subarray) { |
| 41 | + if (subarray.length < 2) return false; |
| 42 | + subarray.sort((a, b) => a - b); |
| 43 | + const diff = subarray[1] - subarray[0]; |
| 44 | + for (let i = 2; i < subarray.length; i++) { |
| 45 | + if (subarray[i] - subarray[i - 1] !== diff) return false; |
| 46 | + } |
| 47 | + return true; |
| 48 | + } |
| 49 | +}; |
0 commit comments