Skip to content

Commit 79f60b3

Browse files
committed
Runtime: 1 ms (Top 89.57%) | Memory: 42.40 MB (Top 48.82%)
1 parent 5055c4a commit 79f60b3

File tree

1 file changed

+20
-19
lines changed

1 file changed

+20
-19
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,26 @@
1+
// Runtime: 1 ms (Top 89.57%) | Memory: 42.40 MB (Top 48.82%)
2+
13
class Solution {
2-
public int[] prisonAfterNDays(int[] cells, int n) {
3-
// # Since we have 6 cells moving cells (two wil remain unchaged at anytime)
4-
// # the cycle will restart after 14 iteration
5-
// # 1- The number of days if smaller than 14 -> you brute force O(13)
6-
// # 2- The number is bigger than 14
7-
// # - You do a first round of 14 iteration
8-
// # - Than you do a second round of n%14 iteration
9-
// # ===> O(27)
10-
11-
n = n % 14 == 0 ? 14 : n%14;
12-
int temp[] = new int[cells.length];
4+
public int[] prisonAfterNDays(int[] cells, int N) {
5+
if(N==0) return cells;
6+
int[][] mem=new int[14][8]; // Repeat pattern after day 14, so Day 1 and Day 15 is equal
7+
mem[0][0]=0;
8+
mem[0][7]=0;
9+
for(int i=1;i<7;i++){ // calculating Day 1 and insert at 0th position in mem
10+
if(cells[i-1]==cells[i+1])
11+
mem[0][i]=1;
12+
else
13+
mem[0][i]=0;
14+
}
1315

14-
while(n-- > 0)
15-
{
16-
for(int i=1; i <cells.length- 1; i++)
17-
{
18-
temp[i] = cells[i-1] == cells[i+1]? 1: 0;
16+
for(int j=1;j<14;j++){ // calculating Day 2 to 14 and inserting at position 1 to 13 in mem.
17+
for(int i=1;i<7;i++){
18+
if(mem[j-1][i-1]==mem[j-1][i+1])
19+
mem[j][i]=1;
20+
else
21+
mem[j][i]=0;
1922
}
20-
cells = temp.clone();
2123
}
22-
23-
return cells;
24+
return mem[(N-1)%14]; //return the day modulo 14
2425
}
2526
}

0 commit comments

Comments
 (0)