Follow the hints! - Part 2
If you follow the hints on the problem, it really becomes super straightforward. Calculate the max chain of good indices towards the left and towards the right in two different O(N)-time loops. Iterate a third time to create the return list. Rest is history. Code is down below, cheers, ACC.
Find All Good Indices - LeetCode
2420. Find All Good Indices
Medium
You are given a 0-indexed integer array nums
of size n
and a positive integer k
.
We call an index i
in the range k <= i < n - k
good if the following conditions are satisfied:
- The
k
elements that are just before the indexi
are in non-increasing order. - The
k
elements that are just after the indexi
are in non-decreasing order.
Return an array of all good indices sorted in increasing order.
Example 1:
Input: nums = [2,1,1,1,3,4,1], k = 2 Output: [2,3] Explanation: There are two good indices in the array: - Index 2. The subarray [2,1] is in non-increasing order, and the subarray [1,3] is in non-decreasing order. - Index 3. The subarray [1,1] is in non-increasing order, and the subarray [3,4] is in non-decreasing order. Note that the index 4 is not good because [4,1] is not non-decreasing.
Example 2:
Input: nums = [2,1,1,2], k = 2 Output: [] Explanation: There are no good indices in this array.
Constraints:
n == nums.length
3 <= n <= 105
1 <= nums[i] <= 106
1 <= k <= n / 2
Accepted
10,729
Submissions
31,856
public IListGoodIndices(int[] nums, int k) { int[] left = new int[nums.Length]; left[0] = 0; left[1] = 1; for (int i = 2; i < nums.Length; i++) left[i] = (nums[i - 1] <= nums[i - 2]) ? left[i - 1] + 1 : 1; int[] right = new int[nums.Length]; right[right.Length - 1] = 0; right[right.Length - 2] = 1; for (int i = nums.Length - 3; i >= 0; i--) right[i] = (nums[i + 1] <= nums[i + 2]) ? right[i + 1] + 1 : 1; List retVal = new List (); for (int i = 0; i < nums.Length; i++) if (left[i] >= k && right[i] >= k) retVal.Add(i); return retVal; }
Comments
Post a Comment