-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-112-positioningPlants.js
98 lines (78 loc) · 2.12 KB
/
structy-112-positioningPlants.js
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// https://structy.net/problems/premium/positioning-plants
// p: arr (2d m x n)
// r: num
// costs[i][j] xxx cost[i+1][j]
// recurions W memo
const positioningPlants = (
costs,
pos = 0,
prevType = null,
min = Infinity,
memo = {}
) => {
if (pos === costs.length) return 0;
const prev = pos + "," + prevType;
if (prev in memo) return memo[prev];
for (let i = 0; i < costs[0].length; i++) {
const costAtI = costs[pos][i];
i !== prevType &&
(min = Math.min(
min,
costAtI + positioningPlants(costs, pos + 1, i, min, memo)
));
}
memo[prev] = min;
return min;
};
// recurions WO memo
// const positioningPlants = (costs, pos = 0, prevType = null, min = Infinity) => {
// if (pos === costs.length) return 0;
// for (let i = 0; i < costs[0].length; i++) {
// const costAtI = costs[pos][i];
// i !== prevType && (min = Math.min(min, costAtI + positioningPlants(costs, pos + 1, i, min)));
// }
// return min;
// }
// iteration
// const positioningPlants = (costs) => {
// let prevM;
// let prevP;
// for (let j = 0; j < costs[0].length; j++) {
// let min = Infinity;
// for (let i = 0; i < costs[0].length; i++) {
// i !== j && (min = Math.min(costs[1][j] + costs[0][i], min));
// }
// costs[1][j] = min;
// }
// // main func
// for (let i = 2; i < costs.length; i++) {
// prevM = Math.min(...costs[i - 1]);
// prevP = costs[i - 1].indexOf(prevM);
// for (let j = 0; j < costs[0].length; j++) {
// j !== prevP ? (costs[i][j] += prevM) : (costs[i][j] = Infinity);
// }
// }
// return Math.min(...costs[costs.length - 1]);
// };
console.log(
positioningPlants([
[12, 14, 5],
[6, 3, 2],
])
); // -> 8
// position / type 0 1 2
// 0 [2, 4, 5],
// 1 [6, 3, 2],
console.log(
positioningPlants([
[4, 3, 7],
[6, 1, 9],
[2, 5, 3],
])
); // -> 7, by doing 4 + 1 + 2
// [
// [4, x, 7],
// [x, 1, 9],
// [2, x, 3],
// ];
// base cases: f(i,j) = min( f(i,j) + f(i-1,j-1) )