
Longest Arithmetic Sequence After Changing At Most One Element - LeetCode-3872 Solution
Today we're looking at Longest Arithmetic Sequence After Changing At Most One Element . This is one of those problems that tests your ability to take a step back and precompute states rather than trying to simulate everything brute-force. Let's break it down. The Problem Problem link We're given an integer array nums . A subarray is arithmetic if the difference between consecutive elements is constant. We're allowed to replace at most one element with any integer we want. Return the maximum length of an arithmetic subarray we can form after making this single replacement. Example: Input: nums = [9, 7, 5, 10, 1] Output: 5 Replace 10 with 3 → [9, 7, 5, 3, 1] . Common difference of -2 . Length = 5. Brute Force The obvious approach: iterate through every index, try replacing it, and check how long of an arithmetic subarray you can form. What do you change it to? You look at the surrounding elements to guess the common difference, then scan left and right. Doing this for every index is O(n²
Continue reading on Dev.to Python
Opens in a new tab



