Categories:

Tags:



Problem

An array is monotonic if it is either monotone increasing or monotone decreasing.

An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j].

Given an integer array nums, return true if the given array is monotonic, or false otherwise.

Constraints

  • 1 <= nums.length <= 105
  • -105 <= nums[i] <= 105

Solution

The problem Monotonic Array can be solved by checking for the first occurence of increase or decrease in elements, and then checking if the rest of the array follows the same pattern.

Implementation

static const int fast_io = []()
{
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class Solution
{
  public:
    bool isMonotonic(vector<int> &nums)
    {
        bool init = false;
        bool inc;

        for (int i = 1; i < nums.size(); i++)
        {
            if (nums[i] == nums[i - 1])
                continue;

            bool comp = nums[i] > nums[i - 1];
            if (!init)
            {
                init = true;
                inc = comp;
            }
            else if (inc != comp)
                return false;
        }

        return true;
    }
};