สมมติว่าเรามีอาร์เรย์ nums ค่าทุกตัวเป็นบวก เริ่มที่ index 0 แต่ละค่าแทนความยาวกระโดดสูงสุดที่ตำแหน่งนั้น เป้าหมายคือถึง index สุดท้าย (n-1) ด้วยจำนวนครั้งน้อยที่สุด
ตัวอย่าง: [2,3,1,1,4] ผลลัพธ์ 2 (กระโดด 0→1, แล้ว 1→4)
ขั้นตอนการแก้ปัญหา (Greedy)
end = 0,jumps = 0,farthest = 0- วนลูป
iจาก 0 ถึงlen(nums)-1:farthest = max(farthest, nums[i] + i)- ถ้า
i == endและi != len(nums)-1:jumps += 1end = farthest
- คืนค่า
jumps
ตัวอย่างโค้ด Python
class Solution(object):
def jump(self, nums):
end = 0
jumps = 0
farthest = 0
for i in range(len(nums)):
farthest = max(farthest, nums[i] + i)
if i == end and i != len(nums) - 1:
jumps += 1
end = farthest
return jumps
ob = Solution()
print(ob.jump([3, 4, 3, 0, 1])) # Output: 2
อินพุต / เอาต์พุต
Input: [3, 4, 3, 0, 1]
Output: 2