36 lines
982 B
C#
36 lines
982 B
C#
|
public class Solution {
|
||
|
private static TValue GetOrDefault<TKey, TValue>(Dictionary<TKey, TValue> map, TKey key, TValue defaultValue) {
|
||
|
if (map.TryGetValue(key, out var value)) {
|
||
|
return value;
|
||
|
}
|
||
|
return defaultValue;
|
||
|
}
|
||
|
|
||
|
public int NumberOfArithmeticSlices(int[] nums) {
|
||
|
var n = nums.Length;
|
||
|
var total = 0;
|
||
|
|
||
|
var dp = new Dictionary<long, int>[n];
|
||
|
for (var i = 0; i < n; ++i) {
|
||
|
dp[i] = new Dictionary<long, int>();
|
||
|
}
|
||
|
|
||
|
for (var i = 1; i < n; ++i) {
|
||
|
for (var j = 0; j < i; ++j) {
|
||
|
var diff = (long) nums[i] - nums[j];
|
||
|
|
||
|
if (diff < int.MinValue || diff > int.MaxValue) {
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
int count = GetOrDefault(dp[j], diff, 0);
|
||
|
|
||
|
total += count;
|
||
|
dp[i][diff] = 1 + count + GetOrDefault(dp[i], diff, 0);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return total;
|
||
|
}
|
||
|
}
|