1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00

cs: add “446. Arithmetic Slices II - Subsequence”

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-01-07 23:02:48 +01:00
parent 98dd458942
commit 2dff3c1d16
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,35 @@
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;
}
}