Answer the question
In order to leave comments, you need to log in
Why doesn't the code pass the test in Yandex.Contest?
I solve problems from Yandex.Contest , I can’t understand what the error is.
It is required to find the longest sequence of ones in a binary vector and output its length.
It is desirable to obtain a solution that works in linear time and at the same time passes through the input array only once.
Input format
The first line of the input file contains one number n, n ≤ 10000. Each of the next n lines contains exactly one number — the next element of the array.
Output Format The
output file must contain a single number, the length of the longest sequence of ones in the input array.
The code passes two tests, on the third - the answer is wrong. Help me figure out what the problem is.
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin
});
let values = [];
rl.on('line', (line) => {
values.push(+line);
}).on('close', () => {
const lengthes = [];
let count = 0;
for (let i = 0; i <= values.length; i++) {
const value = values[i];
if (value === 1) {
count = count + 1;
} else {
if (count !== 0) {
lengthes.push(count);
count = 0;
};
};
};
let maxLength = lengthes.length != 0 ? Math.max(...lengthes) : 0;
process.stdout.write(maxLength.toString());
});
Answer the question
In order to leave comments, you need to log in
It looks like you are adding the number n to the array too.
Here is the correct Kotlin code:
fun main(args: Array<String>) {
var s: String?
var m: Int = 0 // Для максимального значения
var count: Int
var old_m: Int = 0 // Для предыдущего максимального значения
s = readLine()!!
count = s?.toInt()
while (count > 0){
s = readLine()!!
if (s == "1"){
m++
}else{
if(old_m < m){
old_m = m
}
m = 0
}
count--
}
if(old_m < m){
old_m = m
}
println(old_m)
}
At you the case when the number can consist of units is not disassembled. Also, judging by the conditions, the loop should start from the second line. The first line is the number of elements (lines) in the array.
My decision:
const readline = require('readline')
const rl = readline.createInterface({
input: process.stdin
})
const lines = []
let counter = 0
let maxcounter = 0
rl.on('line', (line) => {
lines.push(line)
}).on('close', () => {
for (let i = 1; i < lines.length; i++) {
if (/^[1]+$/.test(lines[i])) {
counter = lines[i].length + counter
} else {
if (maxcounter < counter) {
maxcounter = counter
}
counter = 0
}
}
if (maxcounter < counter) {
maxcounter = counter
}
process.stdout.write(maxcounter.toString())
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question