Leetcode 413. Arithmetic Slices
An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. For example, [1, 3, 5, 7, 9]
, [7, 7, 7, 7]
, and [3, -1, -5, -9]
are arithmetic sequences.
Given an integer array nums
, return the number of arithmetic subarrays of nums
.
nums = [1, 2, 3, 4]
3
[1, 2, 3]
, [2, 3, 4]
, and [1, 2, 3, 4]
itself.nums = [1, 3, 5, 7, 9]
6
[1, 3, 5]
, [3, 5, 7]
, [5, 7, 9]
, [1, 3, 5, 7]
, [3, 5, 7, 9]
, and [1, 3, 5, 7, 9]
.nums
?
nums
are integers. The exact range is not specified, but this algorithm should handle typical integer ranges.nums
?
d
between consecutive elements.public class Solution {
public int numberOfArithmeticSlices(int[] nums) {
int n = nums.length;
if (n < 3) return 0; // There need to be at least three to form an arithmetic subarray
int totalCount = 0;
int currentCount = 0;
// Loop through the array while comparing differences
for (int i = 2; i < n; i++) {
// Check if the current element, along with the previous two, form an arithmetic sequence
if (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) {
currentCount += 1;
totalCount += currentCount; // Accumulate the arithmetic subarrays ending at `i`
} else {
currentCount = 0; // Reset the current arithmetic subarray count
}
}
return totalCount;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums1 = {1, 2, 3, 4}; // Expected output: 3
System.out.println(sol.numberOfArithmeticSlices(nums1));
int[] nums2 = {1, 3, 5, 7, 9}; // Expected output: 6
System.out.println(sol.numberOfArithmeticSlices(nums2));
}
}
This solution efficiently finds all possible arithmetic subarrays by keeping track of the ongoing sequences and counting them as we go.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?