มีรายการตำแหน่งรถในช่วงเวลาเท่ากัน หาสับลิสต์ยาวที่สุดที่ความเร็วคงที่ (ความต่างตำแหน่งเท่ากัน)
เช่น positions=[0,4,8,12,6,4,0] ให้ 4 สับลิสต์ [0,4,8,12]
ขั้นตอนการแก้ปัญหา
- เก็บ
distanceเริ่มต้นระหว่าง 2 ตัวแรก - วนตรวจสอบความต่างติดกัน ถ้าเท่า distance เพิ่ม current มิฉะนั้นรีเซ็ต
- อัปเดต
max_cntตลอด - คืนค่า
max_cnt + 1(จำนวนจุด = จำนวนช่วง + 1)
ตัวอย่างโค้ด
class Solution:
def solve(self, positions):
j = 1
max_cnt = current = 0
distance = abs(positions[0] - positions[1])
while j < len(positions):
prev = positions[j-1]
if distance == abs(positions[j] - prev):
current += 1
else:
max_cnt = max(max_cnt, current)
current = 1
distance = abs(positions[j] - prev)
max_cnt = max(max_cnt, current)
j += 1
return max_cnt + 1
ob = Solution()
positions = [0,4,8,12,6,4,0]
print(ob.solve(positions))
อินพุต
[0, 4, 8, 12, 6, 4, 0]
เอาต์พุต
4