Sponsored
Sponsored
This approach involves traversing the array and maintaining two flags: one for checking if the array elements are in increasing order and another for checking if they are in decreasing order. As we iterate through the array, we update these flags accordingly. If the array violates both conditions at any point, it is not monotonic.
Time Complexity: O(n), where n is the length of the array, since we perform a single traversal of the array.
Space Complexity: O(1), as no extra space is utilized apart from the flags.
1public class Solution {
2 public bool IsMonotonic(int[] nums) {
3 bool increasing = true, decreasing = true;
4 for (int i = 1; i < nums.Length; i++) {
5 if (nums[i] > nums[i - 1])
6 decreasing = false;
7 if (nums[i] < nums[i - 1])
8 increasing = false;
9 }
10 return increasing || decreasing;
11 }
12}
In this C# solution, we perform a single scan over the array. By updating the boolean flags for increasing and decreasing, we determine if at least one of the constraints remains true, thereby confirming if the array is monotonic.
In this approach, we perform two separate passes to test for monotonic increase and monotonic decrease independently. The first pass checks for strictly increasing nature, and the second checks for strictly decreasing nature.
Time Complexity: O(n), two passes over the array which are separate checks.
Space Complexity: O(1), with no additional space used beyond flags.
1
The JavaScript function segregates the logic for checking monotonic increase and decrease into separate procedures. With complete and individual scans, it evaluates the overall monotonicity of the input array.