import bisect n = int(input()) Y = list(map(int, input().split())) if n == 0: print(0) exit() current_candidates = {} start = max(0, Y[0] - 1000) end = Y[0] + 1000 for v in range(start, end + 1): cost = abs(Y[0] - v) current_candidates[v] = cost prev_sorted = sorted(current_candidates.keys()) for i in range(1, n): # Prepare min_prefix using prev_sorted min_prefix = {} min_so_far = float('inf') for v in prev_sorted: if current_candidates[v] < min_so_far: min_so_far = current_candidates[v] min_prefix[v] = min_so_far new_candidates = {} yi = Y[i] # Determine the search range for current v_i if prev_sorted: lower_bound = prev_sorted[0] else: break # should not happen as n >=1 start_i = max(lower_bound, yi - 1000) end_i = yi + 1000 # Iterate possible v_i in the range, using step 1 for integer v_i for v_i in range(start_i, end_i + 1): # Find the largest v_prev <= v_i using binary search on prev_sorted idx = bisect.bisect_right(prev_sorted, v_i) - 1 if idx < 0: continue # no valid v_prev <= v_i best_v_prev = prev_sorted[idx] current_min = min_prefix[best_v_prev] cost = current_min + abs(yi - v_i) # Update new_candidates if v_i not in new_candidates or cost < new_candidates[v_i]: new_candidates[v_i] = cost # Update for next iteration current_candidates = new_candidates if not current_candidates: break # no possible sequence, though problem states n>=1 prev_sorted = sorted(current_candidates.keys()) if current_candidates: print(min(current_candidates.values())) else: print(0)