| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | using LeetCode.Core.Models; |
| | 13 | |
|
| | 14 | | namespace LeetCode.Algorithms.FindTheMinimumAndMaximumNumberOfNodesBetweenCriticalPoints; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class FindTheMinimumAndMaximumNumberOfNodesBetweenCriticalPointsIterative : |
| | 18 | | IFindTheMinimumAndMaximumNumberOfNodesBetweenCriticalPoints |
| | 19 | | { |
| | 20 | | /// <summary> |
| | 21 | | /// Time complexity - O(n) |
| | 22 | | /// Space complexity - O(n) |
| | 23 | | /// </summary> |
| | 24 | | /// <param name="head"></param> |
| | 25 | | /// <returns></returns> |
| | 26 | | public int[] NodesBetweenCriticalPoints(ListNode? head) |
| 3 | 27 | | { |
| 3 | 28 | | if (head?.next?.next == null) |
| 1 | 29 | | { |
| 1 | 30 | | return [-1, -1]; |
| | 31 | | } |
| | 32 | |
|
| 2 | 33 | | var criticalPoints = new List<int>(); |
| 2 | 34 | | var prev = head; |
| 2 | 35 | | var curr = head.next; |
| 2 | 36 | | var next = head.next.next; |
| | 37 | |
|
| 2 | 38 | | var index = 1; |
| | 39 | |
|
| 14 | 40 | | while (next != null) |
| 12 | 41 | | { |
| 12 | 42 | | if ((curr.val > prev.val && curr.val > next.val) || (curr.val < prev.val && curr.val < next.val)) |
| 5 | 43 | | { |
| 5 | 44 | | criticalPoints.Add(index); |
| 5 | 45 | | } |
| | 46 | |
|
| 12 | 47 | | prev = curr; |
| 12 | 48 | | curr = next; |
| 12 | 49 | | next = next.next; |
| 12 | 50 | | index++; |
| 12 | 51 | | } |
| | 52 | |
|
| 2 | 53 | | if (criticalPoints.Count < 2) |
| 0 | 54 | | { |
| 0 | 55 | | return [-1, -1]; |
| | 56 | | } |
| | 57 | |
|
| 2 | 58 | | var minDistance = int.MaxValue; |
| 2 | 59 | | var maxDistance = criticalPoints[^1] - criticalPoints[0]; |
| | 60 | |
|
| 10 | 61 | | for (var i = 1; i < criticalPoints.Count; i++) |
| 3 | 62 | | { |
| 3 | 63 | | minDistance = Math.Min(minDistance, criticalPoints[i] - criticalPoints[i - 1]); |
| 3 | 64 | | } |
| | 65 | |
|
| 2 | 66 | | return [minDistance, maxDistance]; |
| 3 | 67 | | } |
| | 68 | | } |