cs: add “446. Arithmetic Slices II - Subsequence”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
98dd458942
commit
2dff3c1d16
1 changed files with 35 additions and 0 deletions
35
cs/arithmetic-slices-ii-subsequence.cs
Normal file
35
cs/arithmetic-slices-ii-subsequence.cs
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue