คำอธิบายปัญหา
ให้อาร์เรย์ A หาความยาวซับอาร์เรย์ติดต่อกันสั้นที่สุดที่ผลรวม ≥ K หากไม่มีคืน -1
ตัวอย่าง
A = [5,3,-2,2,1], K = 6 → Output: 2 (ซับอาร์เรย์ [5,3])
แนวทางแก้ปัญหา: Monotonic Deque + Prefix Sum
คำนวณ prefix sum: P[i] = A[0]+...+A[i] รักษา deque ของ index ที่ P[index] เพิ่มขึ้น (monotonic increasing):
ต้องการหา i
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int shortestSubarray(vector<int>& A, int K) {
int n = A.size(), ans = n+1;
deque<int> dq;
for(int i=0; iความซับซ้อน