|
| 1 | +/** |
| 2 | + * [2367] Number of Arithmetic Triplets |
| 3 | + * |
| 4 | + * 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: |
| 5 | + * |
| 6 | + * i < j < k, |
| 7 | + * nums[j] - nums[i] == diff, and |
| 8 | + * nums[k] - nums[j] == diff. |
| 9 | + * |
| 10 | + * Return the number of unique arithmetic triplets. |
| 11 | + * |
| 12 | + * Example 1: |
| 13 | + * |
| 14 | + * Input: nums = [0,1,4,6,7,10], diff = 3 |
| 15 | + * Output: 2 |
| 16 | + * Explanation: |
| 17 | + * (1, 2, 4) is an arithmetic triplet because both 7 - 4 == 3 and 4 - 1 == 3. |
| 18 | + * (2, 4, 5) is an arithmetic triplet because both 10 - 7 == 3 and 7 - 4 == 3. |
| 19 | + * |
| 20 | + * Example 2: |
| 21 | + * |
| 22 | + * Input: nums = [4,5,6,7,8,9], diff = 2 |
| 23 | + * Output: 2 |
| 24 | + * Explanation: |
| 25 | + * (0, 2, 4) is an arithmetic triplet because both 8 - 6 == 2 and 6 - 4 == 2. |
| 26 | + * (1, 3, 5) is an arithmetic triplet because both 9 - 7 == 2 and 7 - 5 == 2. |
| 27 | + * |
| 28 | + * |
| 29 | + * Constraints: |
| 30 | + * |
| 31 | + * 3 <= nums.length <= 200 |
| 32 | + * 0 <= nums[i] <= 200 |
| 33 | + * 1 <= diff <= 50 |
| 34 | + * nums is strictly increasing. |
| 35 | + * |
| 36 | + */ |
| 37 | +pub struct Solution {} |
| 38 | + |
| 39 | +// problem: https://leetcode.com/problems/number-of-arithmetic-triplets/ |
| 40 | +// discuss: https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/?currentPage=1&orderBy=most_votes&query= |
| 41 | + |
| 42 | +// submission codes start here |
| 43 | + |
| 44 | +impl Solution { |
| 45 | + pub fn arithmetic_triplets(nums: Vec<i32>, diff: i32) -> i32 { |
| 46 | + nums.iter().fold(0, |acc, &x| { |
| 47 | + if nums.contains(&(x + diff)) && nums.contains(&(x + diff * 2)) { |
| 48 | + acc + 1 |
| 49 | + } else { |
| 50 | + acc |
| 51 | + } |
| 52 | + }) |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +// submission codes end |
| 57 | + |
| 58 | +#[cfg(test)] |
| 59 | +mod tests { |
| 60 | + use super::*; |
| 61 | + |
| 62 | + #[test] |
| 63 | + fn test_2367_example_1() { |
| 64 | + let nums = vec![0, 1, 4, 6, 7, 10]; |
| 65 | + let diff = 3; |
| 66 | + |
| 67 | + let result = 2; |
| 68 | + |
| 69 | + assert_eq!(Solution::arithmetic_triplets(nums, diff), result); |
| 70 | + } |
| 71 | + |
| 72 | + #[test] |
| 73 | + fn test_2367_example_2() { |
| 74 | + let nums = vec![4, 5, 6, 7, 8, 9]; |
| 75 | + let diff = 2; |
| 76 | + |
| 77 | + let result = 2; |
| 78 | + |
| 79 | + assert_eq!(Solution::arithmetic_triplets(nums, diff), result); |
| 80 | + } |
| 81 | +} |
0 commit comments