Sliding Window
Written By PIRATE KING
O(n)
n = size(array)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# i | |
# nums: [5,7,2,8] | |
# j | |
def longestWindow(nums: List[int]) -> int: | |
j = 0, ans | |
for i in range(nums): | |
# code using nums[i] to update the state | |
# that might invalidate the window | |
while invalid(): | |
# code using nums[j] to update the state | |
# and shrink the left edge while the window is invalid | |
j += 1 | |
# longest window so far = len([i, j]) | |
ans = max(ans, i - j + 1); | |
return ans | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// i | |
// nums: [5,7,2,8] | |
// j | |
int longestWindow(int[] nums) { | |
int max; | |
for (int i = 0, j = 0; i < nums.length; i++) { | |
// code using nums[i] to update the state | |
// that might invalidate the window | |
for (; invalid(); j++) { | |
// code using nums[j] to update the state | |
// and shrink the left edge while the window is invalid | |
} | |
// longest window so far = length([i, j]) | |
max = max(ans, i - j + 1); | |
} | |
return max; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# i | |
# nums: [5,7,2,8] | |
# j | |
def longestWindow(nums: List[int]) -> int: | |
i = j = 0; | |
for i in range(nums): | |
# code using nums[i] to update the state | |
# that might invalidate the window | |
if invalid(): | |
# code using nums[j] to update the state | |
# and shift the window sideways. | |
# the window grows if the state is valid | |
# and shifts if it's invalid. | |
j += 1 | |
# the maximum size of the window | |
return i - j | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// i | |
// nums: [5,7,2,8] | |
// j | |
int longestWindow(int[] nums) { | |
int i = 0, j = 0; | |
for (; i < nums.length; i++) { | |
// code using nums[i] to update the state | |
// that might invalidate the window | |
if (invalid()) { | |
// code using nums[j] to update the state | |
// and shift the window sideways. | |
// the window grows if the state is valid | |
// and shifts if it's invalid. | |
j++; | |
} | |
} | |
return i - j; // the maximum size of the window | |
} |