1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-10 00:09:06 +01:00
LeetCode/cs/arithmetic-slices-ii-subsequence.cs
Matej Focko 2dff3c1d16
cs: add “446. Arithmetic Slices II - Subsequence”
Signed-off-by: Matej Focko <mfocko@redhat.com>
2024-01-07 23:02:48 +01:00

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