1658.cpp (553B)
1 class Solution { 2 public: 3 int minOperations(const vector<int> &nums, int x) { 4 const int goal = accumulate(begin(nums), end(nums), 0) - x; 5 if (goal < 0) return -1; 6 if (goal == 0) return nums.size(); 7 8 int sum = 0, start = 0, end = 0, res = 0; 9 for (int i = 0; i < nums.size(); i++) { 10 sum += nums[i]; 11 while (sum > goal) 12 sum -= nums[start++]; 13 if (sum == goal) res = max(res, i - start + 1); 14 } 15 16 return res != 0 ? nums.size() - res : -1; 17 } 18 };