สมมติว่ามีรายการตัวเลข nums และค่า k ต้องการหาความยาวสับลิสต์ (subarray) ยาวที่สุดที่ความต่างสัมบูรณ์ระหว่างค่ามากที่สุดและน้อยที่สุด ≤ k
ตัวอย่าง: nums = [2, 4, 6, 10], k = 4 ผลลัพธ์ 3 เลือก [2, 4, 6] ความต่าง 4
ขั้นตอนการแก้ปัญหา
- ใช้ deque 2 ตัว:
maxd(เก็บค่ามากสุด),mind(เก็บค่าน้อยสุด) i = 0, res = 1- วน
j, aในenumerate(A):- ขณะ
maxdและa > maxd[-1]:maxd.pop() - ขณะ
mindและa < mind[-1]:mind.pop() - เพิ่ม
aเข้าmaxdและmind - ขณะ
maxd[0] - mind[0] > limit:- ถ้า
maxd[0] == A[i]:maxd.popleft() - ถ้า
mind[0] == A[i]:mind.popleft() i += 1
- ถ้า
res = max(res, j - i + 1)
- ขณะ
- คืน
res
ตัวอย่างโค้ด
from collections import deque, defaultdict
class Solution:
def solve(self, A, limit):
maxd = deque()
mind = deque()
i = 0
res = 1
for j, a in enumerate(A):
while maxd and a > maxd[-1]:
maxd.pop()
while mind and a < mind[-1]:
mind.pop()
maxd.append(a)
mind.append(a)
while maxd[0] - mind[0] > limit:
if maxd[0] == A[i]:
maxd.popleft()
if mind[0] == A[i]:
mind.popleft()
i += 1
res = max(res, j - i + 1)
return res
ob = Solution()
nums = [2, 4, 6, 10]
k = 4
print(ob.solve(nums, k))
อินพุต
[2, 4, 6, 10], 4
เอาต์พุต
3