-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution957.cs
49 lines (40 loc) · 1.17 KB
/
Solution957.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System.Text;
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution957
{
/// <summary>
/// 957. Prison Cells After N Days - Medium
/// <a href="https://leetcode.com/problems/prison-cells-after-n-days">See the problem</a>
/// </summary>
public int[] PrisonAfterNDays(int[] cells, int n)
{
var seen = new Dictionary<string, int>();
for (int i = 0; i < n; i++)
{
var nextDayCells = NextDay(cells);
var key = string.Join(",", nextDayCells);
if (!seen.ContainsKey(key))
{
seen[key] = i;
cells = nextDayCells;
}
else
{
var loopLength = i - seen[key];
var remainingDays = (n - i) % loopLength;
return PrisonAfterNDays(cells, remainingDays);
}
}
return cells;
}
private int[] NextDay(int[] cells)
{
var next = new int[cells.Length];
for (int i = 1; i < cells.Length - 1; i++)
{
next[i] = cells[i - 1] == cells[i + 1] ? 1 : 0;
}
return next;
}
}