Description

You are given a 0-indexed, strictly increasing integer array nums and a positive integer diff. A triplet (i, j, k) is an arithmetic triplet if the following conditions are met:

i < j < k, nums[j] - nums[i] == diff, and nums[k] - nums[j] == diff. Return the number of unique arithmetic triplets.

You are given a 0-indexed array nums of length n.

The distinct difference array of nums is an array diff of length n such that diff[i] is equal to the number of distinct elements in the suffix nums[i + 1, …, n - 1] subtracted from the number of distinct elements in the prefix nums[0, …, i].

Return the distinct difference array of nums.

Note that nums[i, …, j] denotes the subarray of nums starting at index i and ending at index j inclusive. Particularly, if i > j then nums[i, …, j] denotes an empty subarray.

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
var arithmeticTriplets = function (nums, diff) {
  let result = 0;
  for (let i = 0; i < nums?.length; i++) {
    let item = nums[i];
    let stack = [item];
    for (let j = i + 1; j < nums?.length; j++) {
      let last = [...stack].pop();
      if (nums[j] - last === diff) {
        stack.push(nums[j]);
        console.log('stack:', stack);
      }
      if (stack?.length === 3) {
        result++;
        break;
      }
    }
  }
  return result;
};