2863. Maximum Length of Semi-Decreasing Subarrays

118 阅读1分钟

image.png

方法

  • compare the first and last elements in the window
  • decrease the window size till we find the answer
  • 尽管从理论上看这个代码的时间复杂度看起来像是 n2
  • 由于每个元素对最多只被检查一次,实际的操作数是线性的,因此时间复杂度为 on
class Solution {
    public int maxSubarrayLength(int[] nums) {
        int size = nums.length;
        while (size > 0) {
            for (int i = 0; i + size - 1 < nums.length; i++) {
                if (nums[i] > nums[i + size - 1]) {
                    return size;
                }
            }
            size--;
        }
        return size;
    }
}