สมมติว่าเรามีรายการตัวเลข nums หาความยาวซับลิสต์ (subarray ติดกัน) ยาวที่สุดที่ 2 * min(sublist) > max(sublist)
ตัวอย่าง: nums = [10, 2, 6, 6, 4, 4] ผลลัพธ์ 4 (ซับลิสต์ [6, 6, 4, 4] เพราะ 2×4 > 6)
ขั้นตอนการแก้ปัญหา (Sliding Window + Deque)
ret = 0- สร้าง deque
minq(เก็บ index ค่าเพิ่มขึ้น) และmaxq(เก็บ index ค่าลดลง) l = 0,r = 0- วนลูป while
r < len(nums):n = nums[r]- รักษา
minq: whileminqและn < nums[minq[-1]]:minq.pop()แล้วminq.append(r) - รักษา
maxq: whilemaxqและn > nums[maxq[-1]]:maxq.pop()แล้วmaxq.append(r) r += 1- while
l < rและnums[minq[0]] * 2 <= nums[maxq[0]]:- ถ้า
minq[0] == l:minq.popleft() - ถ้า
maxq[0] == l:maxq.popleft() l += 1
- ถ้า
ret = max(ret, r - l)
- คืนค่า
ret
ตัวอย่างโค้ด Python
class Solution:
def solve(self, nums):
from collections import deque
ret = 0
minq, maxq = deque(), deque()
l, r = 0, 0
while r < len(nums):
n = nums[r]
while minq and n < nums[minq[-1]]:
minq.pop()
minq.append(r)
while maxq and n > nums[maxq[-1]]:
maxq.pop()
maxq.append(r)
r += 1
while l < r and nums[minq[0]] * 2 <= nums[maxq[0]]:
if minq[0] == l:
minq.popleft()
if maxq[0] == l:
maxq.popleft()
l += 1
ret = max(ret, r - l)
return ret
ob = Solution()
nums = [10, 2, 6, 6, 4, 4]
print(ob.solve(nums)) # Output: 4
อินพุต / เอาต์พุต
Input: [10, 2, 6, 6, 4, 4]
Output: 4