alexjercan/bugnet huggingface dataset:
Problem p03160 (Python) — buggy submission, verdict: Runtime Error

n = int(input())
h = list(map(int, input().split()))
p0, p1 = 0, abs(h[1] - h[0])
for i in range(2, n):
    p2 = min(p1 + abs(h[i] - h[i - 1]), p0 + abs(h[i] - h[i - 2]))
    p0, p1 = p1, p2
print(p1)


Error: ValueError: not enough values to unpack (expected 2, got 1)
Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03160/Python/s516514400.py", line 19, in <module>
    main()
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03160/Python/s516514400.py", line 8, in main
    N, K = map(int, f.readline().split())
ValueError: not enough values to unpack (expected 2, got 1)


Fixed submission:

import sys

# import numpy as np


def main():
    f = sys.stdin.buffer
    N, K = map(int, f.readline().split())
    H = list(map(int, f.readline().split()))
    dp = [0] * N
    for i in range(1, N):
        dp[i] = min(
            dp[i - k - 1] + abs(H[i] - H[i - k - 1]) for k in range(K) if i - k - 1 >= 0
        )
    print(dp[-1])


if __name__ == "__main__":
    main()
Problem p03160 (Python) — buggy submission, verdict: Runtime Error

def solve(n):
    table = [0 for i in range(N + 1)]
    for i in range(1, n + 1):
        if i == 1:
            table[1] = 0
        elif i == 2:
            table[2] = abs(H[2] - H[1])
        else:
            table[i] = min(
                table[i - 1] + abs(H[i] - H[i - 1]), table[i - 2] + abs(H[i] - H[i - 2])
            )
    return table[n]


if __name__ == "__main__":
    N = int(input())
    H = [0] + [int(x) for x in input().split(" ")]

    print(solve(N))


Error: RuntimeError: can't start new thread
Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03160/Python/s452152081.py", line 53, in <module>
    main_thread.start()
  File "/usr/lib/python3.10/threading.py", line 935, in start
    _start_new_thread(self._bootstrap, ())
RuntimeError: can't start new thread


Fixed submission:

import sys
import threading

sys.setrecursionlimit(200000000)
threading.stack_size(134217728)


class SearchProblem(object):
    def __init__(self, N, H):
        self.N = N
        self.H = H

    def isEnd(self, i):
        return i == self.N

    def succ(self, i):
        res = []
        if i + 1 <= self.N:
            res.append((i + 1, abs(self.H[i + 1] - self.H[i])))
        if i + 2 <= self.N:
            res.append((i + 2, abs(self.H[i + 2] - self.H[i])))
        return res


def solve(problem: SearchProblem):
    memo = {}

    def future_cost(s):
        if s in memo:
            return memo[s]

        if problem.isEnd(s):
            memo[s] = 0
            return 0
        else:
            memo[s] = min(
                cost + future_cost(next_state) for next_state, cost in problem.succ(s)
            )
            return memo[s]

    return future_cost(1)


def main():
    N = int(input())
    H = [None] + [int(x) for x in input().split(" ")]
    problem = SearchProblem(N, H)
    print(solve(problem))


if __name__ == "__main__":
    main_thread = threading.Thread(target=main)
    main_thread.start()
    main_thread.join()
Problem p03160 (Python) — buggy submission, verdict: Time Limit Exceeded

n = int(input())
h = list(map(int, input().split()))

# dp[i][j]: 足場iまで見た時 jまでの最小コスト
dp = [0 for i in range(n)]

dp[1] = abs(h[1] - h[0])

for i in range(n):
    if i == 0 or i == 1:
        continue

    cost1jump = dp[i - 1] + abs(h[i] - h[i - 1])
    cost2jump = dp[i - 2] + abs(h[i] - h[i - 2])
    dp[i] = min(cost1jump, cost2jump)

print(dp[-1])


Error: TLE

Fixed submission:

n = int(input())
h = list(map(int, input().split()))

# dp[i][j]: 足場iまで見た時 jまでの最小コスト
dp = [[0 for j in range(n)] for i in range(n)]

dp[1][1] = abs(h[1] - h[0])

for i in range(n):
    if i == 0 or i == 1:
        continue

    dp[i] = dp[i - 1]

    cost1jump = dp[i - 1][i - 1] + abs(h[i] - h[i - 1])
    cost2jump = dp[i - 1][i - 2] + abs(h[i] - h[i - 2])
    dp[i][i] = min(cost1jump, cost2jump)

print(dp[-1][-1])
Problem p03160 (Python) — buggy submission, verdict: Runtime Error

N = int(input())
heights = list(map(int, input().strip().split()))

dp = [float("inf") for _ in range(N)]

dp[0] = 0
if N > 1:
    dp[1] = abs(heights[1] - heights[0])


for i in range(2, N):
    dp[i] = min(
        dp[i],
        dp[i - 1] + abs(heights[i] - heights[i - 1]),
        dp[i - 2] + abs(heights[i] - heights[i - 2]),
    )

print(dp[N - 1])


Error: TypeError: '>' not supported between instances of 'builtin_function_or_method' and 'int'
Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03160/Python/s290255807.py", line 9, in <module>
    if len > 1:
TypeError: '>' not supported between instances of 'builtin_function_or_method' and 'int'


Fixed submission:

import math

N = int(input())
heights = list(map(int, input().strip().split()))

dp = [math.inf for _ in range(N)]

dp[0] = 0
if len > 1:
    dp[1] = abs(heights[1] - heights[0])


for i in range(2, N):
    dp[i] = min(
        dp[i],
        dp[i - 1] + abs(heights[i] - heights[i - 1]),
        dp[i - 2] + abs(heights[i] - heights[i - 2]),
    )

print(dp[N - 1])
Problem p03160 (Python) — buggy submission, verdict: Runtime Error

def sub():
    N = int(input())
    hs = [int(e) for e in input().split()]
    optimal_values = [None for _ in range(N)]
    optimal_values[0] = 0
    for i in range(1, N):
        if i > 1:
            a = optimal_values[i - 1] + abs(hs[i] - hs[i - 1])
            b = optimal_values[i - 2] + abs(hs[i] - hs[i - 2])
            optimal_values[i] = min(a, b)
        else:
            optimal_values[i] = optimal_values[i - 1] + abs(hs[i] - hs[i - 1])
    print(optimal_values[-1])


sub()


Error: 0

Fixed submission:

def sub():
    N = int(input())
    hs = [int(e) for e in input().split()]

    def optimal_value(a_index):
        if a_index >= N - 1:
            return 0

        if a_index < N - 2:
            a = optimal_value(a_index + 1) + abs(hs[a_index + 1] - hs[a_index])
            b = optimal_value(a_index + 2) + abs(hs[a_index + 2] - hs[a_index])
            return min(a, b)
        else:
            return optimal_value(a_index + 1) + abs(hs[a_index + 1] - hs[a_index])

    print(optimal_value(0))


sub()
Problem p03160 (Python) — buggy submission, verdict: Runtime Error

import sys

sys.setrecursionlimit(500000)
N = int(input())
h = [int(i) for i in input().split()]

memo = [float("inf")] * N
memo[0], memo[1] = 0, abs(h[1] - h[0])


def frog(ith):
    if memo[ith] != float("inf"):
        return memo[ith]
    memo[ith] = min(
        frog(ith - 1) + abs(h[ith] - h[ith - 1]),
        frog(ith - 2) + abs(h[ith] - h[ith - 2]),
    )
    return memo[ith]


print(frog(N - 1))


Error: 0

Fixed submission:

N = int(input())
h = [int(i) for i in input().split()]

memo = [float("inf")] * N
memo[0], memo[1] = 0, abs(h[1] - h[0])


def frog(ith):
    if memo[ith] != float("inf"):
        return memo[ith]
    memo[ith] = min(
        frog(ith - 1) + abs(h[ith] - h[ith - 1]),
        frog(ith - 2) + abs(h[ith] - h[ith - 2]),
    )
    return memo[ith]


print(frog(N - 1))
Problem p03160 (Python) — buggy submission, verdict: Runtime Error

import functools
import threading
import sys


class SearchProblem(object):
    def __init__(self, N, H):
        self.N = N
        self.H = H

    def isEnd(self, i):
        return i == self.N

    def succ(self, i):
        res = []
        if i + 1 <= self.N:
            res.append((i + 1, abs(self.H[i + 1] - self.H[i])))
        if i + 2 <= self.N:
            res.append((i + 2, abs(self.H[i + 2] - self.H[i])))
        return res


def solve(problem: SearchProblem):
    @functools.lru_cache(maxsize=None)
    def future_cost(s):
        if problem.isEnd(s):
            return 0
        else:
            return min(
                cost + future_cost(next_state) for next_state, cost in problem.succ(s)
            )

    return future_cost(1)


def main():
    N = int(input())
    H = [None] + [int(x) for x in input().split(" ")]
    problem = SearchProblem(N, H)
    print(solve(problem))


if __name__ == "__main__":

    sys.setrecursionlimit(1024 * 1024 * 2)
    threading.stack_size(128 * 1024 * 1024 * 2)
    threading.Thread(target=main).start()


Error: RuntimeError: can't start new thread
Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03160/Python/s280441279.py", line 47, in <module>
    threading.Thread(target=main).start()
  File "/usr/lib/python3.10/threading.py", line 935, in start
    _start_new_thread(self._bootstrap, ())
RuntimeError: can't start new thread


Fixed submission:

import functools
import threading
import sys


class SearchProblem(object):
    def __init__(self, N, H):
        self.N = N
        self.H = H

    def isEnd(self, i):
        return i == self.N

    def succ(self, i):
        res = []
        if i + 1 <= self.N:
            res.append((i + 1, abs(self.H[i + 1] - self.H[i])))
        if i + 2 <= self.N:
            res.append((i + 2, abs(self.H[i + 2] - self.H[i])))
        return res


def solve(problem: SearchProblem):
    @functools.lru_cache(maxsize=None)
    def future_cost(s):
        if problem.isEnd(s):
            return 0
        else:
            return min(
                cost + future_cost(next_state) for next_state, cost in problem.succ(s)
            )

    return future_cost(1)


def main():
    N = int(input())
    H = [None] + [int(x) for x in input().split(" ")]
    problem = SearchProblem(N, H)
    print(solve(problem))


if __name__ == "__main__":

    sys.setrecursionlimit(1024 * 1024)
    threading.stack_size(128 * 1024 * 1024)
    threading.Thread(target=main).start()
Problem p03160 (Python) — buggy submission, verdict: Time Limit Exceeded

n = int(input())
initial_vals = list(map(int, input().split(" ")))


# print(calc(0, n - 1))


arr = [0 for x in range(n)]

arr[1] = abs(initial_vals[0] - initial_vals[1])

for i in range(2, len(arr)):
    arr[i] = min(
        arr[i - 1] + abs(initial_vals[i - 1] - initial_vals[i]),
        arr[i - 2] + abs(initial_vals[i - 2] - initial_vals[i]),
    )

print(arr[n - 1])


Error: TLE

Fixed submission:

n = int(input())
initial_vals = list(map(int, input().split(" ")))


table = [[None for x in range(n)] for x in range(n)]


def calc(from_stone, to_stone):
    if table[from_stone][to_stone] is not None:
        return table[from_stone][to_stone]
    elif (to_stone - from_stone) == 1:
        table[from_stone][to_stone] = abs(
            initial_vals[from_stone] - initial_vals[to_stone]
        )
        return table[from_stone][to_stone]
    elif (to_stone - from_stone) == 2:
        table[from_stone][to_stone] = min(
            abs(initial_vals[from_stone] - initial_vals[to_stone - 1])
            + abs(initial_vals[to_stone - 1] - initial_vals[to_stone]),
            abs(initial_vals[from_stone] - initial_vals[to_stone]),
        )
        return table[from_stone][to_stone]
    else:
        table[from_stone][to_stone] = min(
            calc(from_stone, to_stone - 1) + calc(to_stone - 1, to_stone),
            calc(from_stone, to_stone - 2) + calc(to_stone - 2, to_stone),
        )
        return table[from_stone][to_stone]


print(calc(0, n - 1))
Problem p03161 (Python) — buggy submission, verdict: Time Limit Exceeded

import functools
import threading
import sys


def main():
    @functools.lru_cache(maxsize=None)
    def solve(n):
        if n == 1:
            return 0
        else:
            return min(
                solve(n - k) + abs(H[n] - H[n - k])
                for k in range(1, K + 1)
                if n - k >= 1
            )

    N, K = [int(x) for x in input().split(" ")]
    H = [None] + [int(x) for x in input().split(" ")]
    print(solve(N))


if __name__ == "__main__":

    sys.setrecursionlimit(1024 * 1024 * 2)
    threading.stack_size(128 * 1024 * 1024 * 2)
    threading.Thread(target=main).start()


Error: TLE

Fixed submission:

import functools
import threading
import sys


class SearchProblem(object):
    def __init__(self, N, H, K):
        self.N = N
        self.H = H
        self.K = K

    def isEnd(self, i):
        return i == self.N

    def succ(self, i):
        return [
            (i + k, abs(self.H[i + k] - self.H[i]))
            for k in range(1, self.K + 1)
            if i + k <= self.N
        ]


def solve(problem: SearchProblem):
    @functools.lru_cache(maxsize=None)
    def future_cost(s):
        if problem.isEnd(s):
            return 0
        else:
            return min(
                cost + future_cost(next_state) for next_state, cost in problem.succ(s)
            )

    return future_cost(1)


def main():
    N, K = [int(x) for x in input().split(" ")]
    H = [None] + [int(x) for x in input().split(" ")]
    problem = SearchProblem(N, H, K)
    print(solve(problem))


if __name__ == "__main__":

    sys.setrecursionlimit(1024 * 1024 * 2)
    threading.stack_size(128 * 1024 * 1024 * 2)
    threading.Thread(target=main).start()
Problem p03161 (Python) — buggy submission, verdict: Time Limit Exceeded

def main():
    n, k = map(int, input().split())
    h = list(map(int, input().split()))
    a = [0 for i in range(n)]
    for i in range(1, n):
        a[i] = min([a[j] + abs(h[i] - h[j]) for j in range(max(0, i - k), i)])
    print(a[-1])


if __name__ == "__main__":
    main()


Error: TLE

Fixed submission:

n, k = map(int, input().split())
h = list(map(int, input().split()))
a = [0] * n
a[0] = 0
for i in range(1, n):
    a[i] = min([a[j] + abs(h[i] - h[j]) for j in range(max(0, i - k), i)])
print(a[-1])
Problem p03161 (Python) — buggy submission, verdict: Runtime Error

import numpy as np

N, K = map(int, input().split())
lst = np.array([int(x) for x in input().split()])
dp = np.zeros(N, dtype=int)

for i in range(1, N):
    start = max(i - K, 0)
    dp[i] = np.min(dp[start:i] + np.abs(lst[start:i] - lst[i]))
print(dp[-1])


Error: 0

Fixed submission:

import math

N, K = map(int, input().split())
lst = [int(x) for x in input().split()]
dp = [math.inf] * N
dp[0] = 0
dp[1] = abs(lst[0] - lst[1])
for i in range(2, N):
    j = K
    while j > 0:
        if i - j >= 0:
            dp[i] = min(dp[i], dp[i - j] + abs(lst[i - j] - lst[i]))
        j -= 1
print(dp[-1])
Problem p03161 (Python) — buggy submission, verdict: Runtime Error

import sys

import numba as nb
import numpy as np

input = sys.stdin.readline
INF = float("inf")


@nb.njit
def solve(N, K, h):
    dp = [0] * N
    for i in range(1, N):
        min_cost = INF
        for k in range(1, min(K + 1, i + 1)):
            cost = dp[i - k] + abs(h[i] - h[i - k])
            if cost < min_cost:
                min_cost = cost
        dp[i] = min_cost
    return dp[-1]


def main():
    N, K = map(int, input().split())
    h = np.array(input().split(), dtype=np.int64)

    ans = solve(N, K, h)
    print(ans)


if __name__ == "__main__":
    main()


Error: ModuleNotFoundError: No module named 'numba'
Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03161/Python/s994511645.py", line 3, in <module>
    import numba as nb
ModuleNotFoundError: No module named 'numba'


Fixed submission:

import sys

import numba as nb

input = sys.stdin.readline
INF = float("inf")


@nb.njit
def solve(N, K, h):
    dp = [0] * N
    for i in range(1, N):
        min_cost = INF
        for k in range(1, min(K + 1, i + 1)):
            cost = dp[i - k] + abs(h[i] - h[i - k])
            if cost < min_cost:
                min_cost = cost
        dp[i] = min_cost
    return dp[-1]


def main():
    N, K = map(int, input().split())
    h = tuple(map(int, input().split()))

    ans = solve(N, K, h)
    print(ans)


if __name__ == "__main__":
    main()
Problem p03161 (Python) — buggy submission, verdict: Time Limit Exceeded

import math

n, k = map(int, input().split())
h = list(map(int, input().split()))

dp = [math.inf] * n
dp[0] = 0
for i in range(1, n):
    dp[i] = min(dp[j] + abs(h[i] - h[j]) for j in range(max(0, i - k), i))
print(dp[n - 1])


Error: TLE

Fixed submission:

import math

n, k = map(int, input().split())
h = list(map(int, input().split()))

dp = [math.inf] * n
dp[0] = 0
for i in range(1, n):
    for j in range(max(0, i - k), i):
        dp[i] = min(dp[i], dp[j] + abs(h[i] - h[j]))
print(dp[n - 1])
Problem p03161 (Python) — buggy submission, verdict: Time Limit Exceeded

import sys
import numpy as np


def input():
    return sys.stdin.readline().strip()


def main():
    n, k = map(int, input().split())
    h = np.array(input().split(), dtype=np.int64)
    dp = np.zeros(n, dtype=np.int64)

    for i in range(1, n):
        j = max(0, i - k)
        dp[i] = np.min(np.abs(h[i] - h[j:i]) + dp[j:i])
    print(dp[n - 1])


if __name__ == "__main__":
    main()


Error: TLE

Fixed submission:

import sys


def input():
    return sys.stdin.readline().strip()


def main():
    n, k = map(int, input().split())
    h = list(map(int, input().split()))
    dp = [0] * n
    dp[0] = 0
    dp[1] = abs(h[0] - h[1])

    for i in range(2, n):
        dp[i] = min(abs(h[i] - h[j]) + dp[j] for j in range(max(0, i - k), i))
    print(dp[n - 1])


if __name__ == "__main__":
    main()
Problem p03161 (Python) — buggy submission, verdict: Runtime Error

import sys
import numpy as np

input = sys.stdin.readline

N, K = map(int, input().split())
h = np.array(list(map(int, (input().split()))))

dp = np.full(N, sys.maxsize, dtype=int)

dp[0] = 0

for i in range(1, N):
    s = max(0, i - K)
    dp[i] = min(dp[s:i] + abs(h[i] - h[s:i]))

print(dp[N - 1])


Error: TypeError: unsupported operand type(s) for -: 'list' and 'int'
Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03161/Python/s304743671.py", line 14, in <module>
    dp[i] = min(dp[s:i] + abs(h[s:i] - h[i]))
TypeError: unsupported operand type(s) for -: 'list' and 'int'


Fixed submission:

import sys

input = sys.stdin.readline

N, K = map(int, input().split())
h = list(map(int, (input().split())))

dp = [sys.maxsize] * N

dp[0] = 0

for i in range(1, N):
    s = max(0, i - K)
    dp[i] = min(dp[s:i] + abs(h[s:i] - h[i]))

print(dp[N - 1])
Problem p03161 (Python) — buggy submission, verdict: Time Limit Exceeded

N, K = map(int, input().split())
H = list(map(int, input().split()))
H = [H[0]] * K + H

# dp[i] := 足場iに来るのにかかる最小のコスト
INF = 10**18
dp = [INF] * (K + N)
dp[0] = 0
for i in range(K, N + K):
    h = H[i]
    dp[i] = min(x + abs(y - h) for x, y in zip(dp[i - K : i], H[i - K : i]))
#     for j in range(1, K + 1):
#         v = dp[i - j] + abs(H[i] - H[i - j])
#         dp[i] = min(dp[i], v)
# print('dp', dp)
ans = dp[-1]
print(ans)


Error: TLE

Fixed submission:

N, K = map(int, input().split())
H = list(map(int, input().split()))
H = [H[0]] * K + H

# dp[i] := 足場iに来るのにかかる最小のコスト
INF = 10**18
dp = [INF] * (K + N)
dp[0] = 0
for i in range(1, N + K):
    for j in range(1, K + 1):
        v = dp[i - j] + abs(H[i] - H[i - j])
        dp[i] = min(dp[i], v)
# print('dp', dp)
ans = dp[-1]
print(ans)
Problem p03161 (Python) — buggy submission, verdict: Time Limit Exceeded

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np

N, K = map(int, input().split())
h = list(map(int, input().split()))
# 高速化のためにnumpy使う
h = np.array(h)

# dp[i] = 足場iに移動するのに必要な最小コスト
dp = [0 for _ in range(N)]
# 高速化のためにnumpy使う
dp = np.array(dp)

# DP配列更新
"""
TLEだったやつ
for i in range(1, N):
    # 最小コストで更新する
    max_k = min([i, K]) + 1
    dp[i] = min([dp[i - k] + abs(h[i] - h[i - k]) for k in range(1, max_k)])
"""
for i in range(1, N):
    # 最小コストで更新する
    # K個まとめて移動コストを計算することで高速化
    # ただしマイナスからスタートするような値はスキップする
    s = max(0, i - K)
    dp[i] = np.min(dp[s:i] + np.abs(h[s:i] - h[i]))

print(dp[-1])


Error: TLE

Fixed submission:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

N, K = map(int, input().split())
h = list(map(int, input().split()))

# dp[i] = 足場iに移動するのに必要な最小コスト
dp = [0 for _ in range(N)]

# DP配列更新
for i in range(1, N):
    # 最小コストで更新する
    max_k = min([i, K]) + 1
    dp[i] = min([dp[i - k] + abs(h[i] - h[i - k]) for k in range(1, max_k)])

print(dp[-1])
Problem p03161 (Python) — buggy submission, verdict: Time Limit Exceeded

from math import inf

n, k = map(int, input().split())
a = [int(i) for i in input().split()]
dp = [inf for _ in range(n)]
dp[0] = 0
for i in range(1, n):
    for j in range(1, k + 1):
        if i - j >= 0:
            dp[i] = min(dp[i], abs(a[i] - a[i - j]) + dp[i - j])
        else:
            break

print(dp[-1])


Error: TLE

Fixed submission:

from math import inf

n, k = map(int, input().split())
a = [int(i) for i in input().split()]
dp = [inf for _ in range(n)]
dp[0] = 0
for i in range(1, n):
    for j in range(1, k + 1):
        if i - j >= 0:
            dp[i] = min(dp[i], abs(a[i] - a[i - j]) + dp[i - j])

print(dp[-1])
Problem p03161 (Python) — buggy submission, verdict: Time Limit Exceeded

#!/usr/bin/env python3
# vim: set fileencoding=utf-8

# pylint: disable=unused-import, invalid-name, missing-docstring, bad-continuation


"""Module docstring
"""

import sys
from collections import deque


def solve(values, nb, max_jump_size):
    max_jump_size = min(nb, max_jump_size)
    cost_to = [0]
    for i in range(1, nb):
        new_cost = min(
            cost_to[i - k] + abs(values[i] - values[i - k])
            for k in range(1, max_jump_size + 1)
            if i - k >= 0
        )
        cost_to.append(new_cost)
    return new_cost


def do_job():
    "Do the work"
    # first line is number of test cases
    N, K = map(int, input().split())
    values = list(map(int, input().split()))
    result = solve(values, N, K)
    print(result)


def print_output(testcase, result) -> None:
    "Formats and print result"
    if result is None:
        result = "IMPOSSIBLE"
    print("Case #{}: {}".format(testcase + 1, result))


def main(argv=None):
    "Program wrapper."
    if argv is None:
        argv = sys.argv[1:]
    do_job()
    return 0


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    sys.exit(main())


Error: TLE

Fixed submission:

#!/usr/bin/env python3
# vim: set fileencoding=utf-8

# pylint: disable=unused-import, invalid-name, missing-docstring, bad-continuation


"""Module docstring
"""

import sys
from collections import deque


def solve(values, nb, max_jump_size):
    max_jump_size = min(nb, max_jump_size)
    cost_to = deque([0])
    new_cost = 0
    for i in range(1, nb):
        new_cost = min(
            cost_to[-k] + abs(values[i] - values[i - k])
            for k in range(1, max_jump_size + 1)
            if i - k >= 0
        )
        if i > max_jump_size:
            cost_to.popleft()
        cost_to.append(new_cost)
    return new_cost


def do_job():
    "Do the work"
    # first line is number of test cases
    N, K = map(int, input().split())
    values = list(map(int, input().split()))
    result = solve(values, N, K)
    print(result)


def print_output(testcase, result) -> None:
    "Formats and print result"
    if result is None:
        result = "IMPOSSIBLE"
    print("Case #{}: {}".format(testcase + 1, result))


def main(argv=None):
    "Program wrapper."
    if argv is None:
        argv = sys.argv[1:]
    do_job()
    return 0


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    sys.exit(main())
Problem p03161 (Python) — buggy submission, verdict: Time Limit Exceeded

import sys


def input():
    return sys.stdin.readline().strip()


def main():
    size, jumps = map(int, input().split())
    array = list(map(int, input().split()))
    dp = [999999999] * size
    dp[0] = 0
    dp[1] = abs(array[0] - array[1])
    for i in range(2, size):
        dp[i] = min(
            abs(array[i] - array[j]) + dp[j] for j in range(max(0, i - jumps), i)
        )
    print(dp[size - 1])


if __name__ == "__main__":
    main()


Error: TLE

Fixed submission:

import sys


def input():
    return sys.stdin.readline().strip()


def main():
    n, k = map(int, input().split())
    h = list(map(int, input().split()))
    dp = [0] * n
    dp[0] = 0
    dp[1] = abs(h[0] - h[1])

    for i in range(2, n):
        dp[i] = min(abs(h[i] - h[j]) + dp[j] for j in range(max(0, i - k), i))
    print(dp[n - 1])


if __name__ == "__main__":
    main()