what's the time complexity of this code with sliding window?

64 Views Asked by At

parent for loop has On , while loop has amoritised O n? meaning we consider it O 1? also min and max operations they will be O k but again On in worst case? is it O (n^3) ?

        left=0
        curr_max=0
        for right in range(len(nums)):
            mx =max(nums[left:right+1])
            mn =min(nums[left:right+1])
            if mx - mn <=limit:
                curr_max = max(right - left + 1,curr_max)
            while  mx - mn > limit:
                left+=1
                if max(nums[left:right+1]) - min(nums[left:right+1]) <=limit:
                    curr_max = max(right - left + 1,curr_max)
                    break
        # print(curr_max)
        return curr_max

I am evaluating time complexity for this

1

There are 1 best solutions below

0
Marcin Orlowski On

The worst-case time complexity seems to exceed O(n^2) due to the nested loop structure and the repeated min()/max() calls. It might approach O(n^3) in scenarios where the while loop frequently resets left and the max/min is computed over large slices.