| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 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 | | namespace LeetCode.Algorithms.LongestStrictlyIncreasingOrStrictlyDecreasingSubarray; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class LongestStrictlyIncreasingOrStrictlyDecreasingSubarrayIterative : |
| | | 16 | | ILongestStrictlyIncreasingOrStrictlyDecreasingSubarray |
| | | 17 | | { |
| | | 18 | | /// <summary> |
| | | 19 | | /// Time complexity - O(n) |
| | | 20 | | /// Space complexity - O(1) |
| | | 21 | | /// </summary> |
| | | 22 | | /// <param name="nums"></param> |
| | | 23 | | /// <returns></returns> |
| | | 24 | | public int LongestMonotonicSubarray(int[] nums) |
| | 3 | 25 | | { |
| | 3 | 26 | | var increasingLength = 1; |
| | 3 | 27 | | var decreasingLength = 1; |
| | 3 | 28 | | var maxLength = 1; |
| | | 29 | | |
| | 24 | 30 | | for (var i = 0; i < nums.Length - 1; i++) |
| | 9 | 31 | | { |
| | 9 | 32 | | if (nums[i] > nums[i + 1]) |
| | 4 | 33 | | { |
| | 4 | 34 | | decreasingLength++; |
| | 4 | 35 | | increasingLength = 1; |
| | 4 | 36 | | } |
| | 5 | 37 | | else if (nums[i] < nums[i + 1]) |
| | 1 | 38 | | { |
| | 1 | 39 | | increasingLength++; |
| | 1 | 40 | | decreasingLength = 1; |
| | 1 | 41 | | } |
| | | 42 | | else |
| | 4 | 43 | | { |
| | 4 | 44 | | increasingLength = 1; |
| | 4 | 45 | | decreasingLength = 1; |
| | 4 | 46 | | } |
| | | 47 | | |
| | 9 | 48 | | maxLength = Math.Max(maxLength, Math.Max(increasingLength, decreasingLength)); |
| | 9 | 49 | | } |
| | | 50 | | |
| | 3 | 51 | | return maxLength; |
| | 3 | 52 | | } |
| | | 53 | | } |