Story
Niñez friends from Kakao Elementary School meet a stream with stepping stones on an autumn picnic with Ms. Ryan and are about to cross over to the other side. Ms. Ryan made the following rules so that Niñez and his friends can safely cross the river:
- Stepping stones are placed in a row, and the number of times a kid may step on a stone is written on each stone.
- The number on the stone decreases by one each time a kid steps on them.
- When the number of stepping stones reaches 0, you can no longer step on them.
- A kid can jump, skipping several stones. The maximum number of stones that a kid may skip is given as a parameter k.
- If a kid jumps, you always jump to the nearest stepping stone that isn't 0.
The friends of Niñez are on the left side of the stream, and they must arrive across the right side of the stream to be counted as crossing the stepping stone.
How many kids can cross the river, given an array of initial values on the stones and the parameter k?
Constraints
- The number of Ninez friends who must cross the stepping stone is considered to be unlimited.
- The stones array has a size of at least 1 and has a maximum length of 200,000.
- The initial value of each element in the stones array is a natural number between 1 and 200,000,000.
- k is a natural number greater than or equal to 1 and less than or equal to the length of the stones.
Code review question
How should i revise my code? this is Kakao intern code test. I used loop to change stone numbers when stepped and repeat many times . It returns how many people could cross the river.
Original challenge (in Korean)
Example
stones = [2, 4, 5, 3, 2, 1, 4, 2, 5, 1]
k=3
After the first kid crosses, the stones have the following values:
stones = [1, 3, 4, 2, 1, 0, 3, 1, 4, 0]
The second kid makes it, making two jumps:
stones = [0, 2, 3, 1, 0, 0, 2, 0, 3, 0]
The third kid makes it, making four jumps:
stones = [0, 1, 2, 0, 0, 0, 1, 0, 2, 0]
Now it takes a jump of 4 stones to get to the other side, which is larger than k = 3. So the answer for this input is three kids, or simply 3
.
def solution(stones, k):
num=len(stones)
answer=0
for count in range(max(stones)):
stat=-1
for i in range(num):
if stat==i-1:
if stones[i]==0:
for j in range(i+1,num):
if stones[j]==0:
if j-stat>=k:
return answer
else:
pass
elif stones[j]!=0:
stat=j
stones[j]-=1
break
elif stones[i]!=0:
stat=i
stones[i]-=1
if stat+k>=num:
answer+=1
elif stat+k<num:
return answer
return answer