-
Notifications
You must be signed in to change notification settings - Fork 1
/
minPenalty.js
85 lines (77 loc) · 1.88 KB
/
minPenalty.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
function calculatePenalty(log, closingTime) {
let trimmedLog = log.trim().split(" ");
let penalty = 0;
for (let i = 0; i < closingTime; i++) {
if (trimmedLog[i] === "N") {
penalty++;
}
}
for (let i = closingTime; i < trimmedLog.length; i++) {
if (trimmedLog[i] === "Y") {
penalty++;
}
}
return penalty;
}
let result = calculatePenalty("Y Y N Y", 4);
// console.log(result);
function minPenalty(log) {
let trimmedLog = log.trim().split("");
let minimumPenalty = Infinity;
let result;
for (let i = 0; i <= trimmedLog.length; i++) {
if (calculatePenalty(log, i) < minimumPenalty) {
minimumPenalty = calculatePenalty(log, i);
result = i;
}
}
return result;
}
function parseString(str) {
let trimmedStr = str.trim().split(" ");
let stack = [];
let arr = [];
let penalty = [];
for (let i = 0; i < trimmedStr.length; i++) {
if (trimmedStr[i] !== "END") {
stack.push(trimmedStr[i]);
} else {
// console.log("stack", stack);
let temp = [];
while (stack.length > 0 && stack[stack.length - 1] !== "BEGIN") {
temp.push(stack.pop());
}
stack.pop();
arr.push(temp.reverse().join(" "));
}
}
console.log(arr);
for (let a of arr) {
penalty.push(minPenalty(a));
}
return penalty;
}
let p = parseString("BEGIN BEGIN BEGIN Y Y N Y END Y Y N N END Y N Y N END");
console.log(p);
let re = minPenalty("Y Y N Y");
console.log(re);
// optimised
function bestClosingTime(log) {
let trimmedLog = log.trim().split("");
let minimumPenalty = 0;
let result=0;
let currentPenalty = 0;
for (let i = 0; i < trimmedLog.length; i++) {
if (trimmedLog[i] === 'Y') {
currentPenalty -- ;
if(currentPenalty<minimumPenalty){
minimumPenalty = currentPenalty;
result =i+1;
}
}
else{
currentPenalty++;
}
}
return result;
}