- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 56 lines of C++ from the credited upstream file longest-non-decreasing-subarray-after-replacing-at-most-one-element.cpp.
- The implementation visibly relies on sequence storage.
- 5 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 int longestSubarray(vector<int>& nums) {8 vector<int> right(size(nums), 1);9 for (int i = size(nums) - 2; i >= 0; --i) {10 if (nums[i] <= nums[i + 1]) {11 right[i] = right[i + 1] + 1;12 }13 }14 int result = min(ranges::max(right) + 1, static_cast<int>(size(nums)));15 for (int i = 1, left = 1; i + 1 < size(nums); ++i) {16 if (nums[i - 1] <= nums[i + 1]) {17 result = max(result, left + 1 + right[i + 1]);18 }19 if (nums[i - 1] <= nums[i]) {20 ++left;21 } else {22 left = 1;23 }24 }25 return result;26 }27};28 29303132class Solution2 {33public:34 int longestSubarray(vector<int>& nums) {35 vector<int> left(size(nums), 1);36 for (int i = 0; i + 1 < size(nums); ++i) {37 if (nums[i] <= nums[i + 1]) {38 left[i + 1] = left[i] + 1;39 }40 }41 vector<int> right(size(nums), 1);42 for (int i = size(nums) - 2; i >= 0; --i) {43 if (nums[i] <= nums[i + 1]) {44 right[i] = right[i + 1] + 1;45 }46 }47 int result = min(ranges::max(left) + 1, static_cast<int>(size(nums)));48 for (int i = 1; i + 1 < size(nums); ++i) {49 if (nums[i - 1] <= nums[i + 1]) {50 result = max(result, left[i - 1] + 1 + right[i + 1]);51 }52 }53 return result;54 }55};56