1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-19 09:46:57 +02:00
LeetCode/cs/arithmetic-slices-ii-subsequence.cs
Matej Focko 4763cdbdda
chore(cs): format
Signed-off-by: Matej Focko <mfocko@redhat.com>
2024-03-15 17:22:58 +01:00

35 lines
981 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;
}
}