This column is a summary and induction of various methods for the problem of force deduction algorithm, sorting out the most important ideas and knowledge points and presenting them in the form of mind map. Of course, my detailed explanation of the map will also be added
The purpose is to memorize and recall the key points of the algorithm more conveniently and quickly (you don't have to look at the problem solution every time). After all, the algorithm can't be completely remembered after doing it once. Therefore, this paper is suitable for friends who already know the ideas and methods of problem solving and want to further strengthen understanding and memory, not for friends who contact this problem for the first time (you can go to the power button to see the official solution according to the question number, and then read the content of this article.)
For the directory links of all topics in this column, the order / precautions / skills of brushing algorithm topics, and the source files of mind map, please click This link.
If you want to enter a large factory, the brushing algorithm is essential. You are welcome to punch in the brushing force deduction algorithm together with the blogger. The blogger has synchronously updated the video explanation of the algorithm and the explanation of other articles / maps, which is easier to understand, Welcome to see!
Title Link: https://leetcode-cn.com/problems/longest-turbulent-subarray/solution/si-wei-dao-tu-zheng-li-dong-tai-gui-hua-bswtn/
0. Map arrangement
1. Construction of dynamic programming
After training in the previous topics: Maximum suborder sum, Maximum subsequence product , for this problem of finding the longest array, we can easily think of using dynamic programming to solve it
However, it will be found that the design of dp array in this problem is not as easy as the previous two questions. The most difficult point is that the formation conditions of turbulence sub array are exactly two opposite states, and it is obviously unrealistic for us to use a dp array to represent these two states at the same time. Therefore, we must use two dp arrays to represent different states respectively in this problem Break and push on
The definition and recurrence formula of the two dp arrays are as follows:
When defining the name of dp array, we should try to directly reflect the meaning of dp array up [i] and down [i], so that it can be clear at a glance when writing code. Don't think about the meaning of dp [i] [0] and dp [i] [1] like the official definition
As for the recurrence formula, because the increase and decrease of turbulence subarray are alternating, the dp array of the previous state in the current state must be opposite. The specific dynamic demonstration process can be explained in the corresponding video
Secondly, we need to pay attention to the set one operation in the recursive formula, as shown in the figure below: we see that the fourth number 10 in the array rises from 2 to 10 in front of it, so we use down[i-1] to update the value of up[i], but for down[i], only number 10 meets the requirements, and the previous numbers do not meet the requirements, so its value is 1
It is not too difficult to write the code, but the set one operation mentioned above is very important in space optimization. Without space optimization, the dp array is stored with an array, and the initial value is 1. In fact, whether there is a set one operation in the code has no impact on the final result. However, after space optimization, the dp array only It is stored with a variable whose value changes continuously. If there is no timely set one operation, the final result must be wrong
2. Various conditions of sliding window
This problem can also be solved with the idea of sliding window. The most difficult point of sliding window is to determine the sliding conditions at both ends of the window
The two conditions for the right pointer to slide are well understood, that is, two conditions that meet the requirements. Of course, the conditions for the left pointer to slide are not met, but here is a note: the left pointer does not slide unit by unit, but directly jumps to the position of the right pointer. Because when left < right, [left,right+1] cannot form a "turbulent subarray" , all the numbers in the middle must be unsatisfied, so there is no need to slide one by one
Another difficulty of sliding window is the processing of boundary. For this problem, the window length becomes 1 (i.e. when left and right are equal): at this time, as long as arr[right] ≠ arr[right+1] , right can be shifted to the right by one unit; otherwise, both left and right should be shifted to the right at the same time, skipping the case where the two numbers are equal. The boundary conditions must be considered carefully, otherwise it is easy to make mistakes
Source code
Python:
# 1. Dynamic planning # No space optimization class Solution(object): def maxTurbulenceSize(self, arr: List[int]): N = len(arr) up = [1] * N # The length of the longest turbulent sub array ending at position I and arr [I - 1] < arr [i] down = [1] * N # The length of the longest turbulent sub array ending at position I and arr [I - 1] > arr [i] res = 1 for i in range(1, N): if arr[i - 1] < arr[i]: # The growth and decrease of turbulent subarray are alternating up[i] = down[i - 1] + 1 down[i] = 1 elif arr[i - 1] > arr[i]: up[i] = 1 down[i] = up[i - 1] + 1 else: up[i] = 1 down[i] = 1 res = max(res, up[i], down[i]) return res # Spatial optimization class Solution: def maxTurbulenceSize(self, arr: List[int]) -> int: down, up = 1, 1 # The length of the longest continuous subarray that ends with this element and is Valley / peak res = 1 for i in range(1, len(arr)): if arr[i-1] > arr[i]: down = up + 1 up = 1 elif arr[i-1] < arr[i]: up = down + 1 down = 1 else: down, up = 1, 1 res = max(res, down, up) return res # 2. Sliding window class Solution(object): def maxTurbulenceSize(self, arr: List[int]): n = len(arr) ret = 1 left = right = 0 while right < n - 1 : if left == right : # Special case: window length is 1 if arr[left] == arr[left + 1] : # When the two pointers are equal, the left and right pointers move at the same time left+=1 right+=1 # When the two pointers are not equal, only the right pointer is moved else : # Normal condition: the window length is not 1 # In the following two cases, you can move the right pointer to expand the window if arr[right - 1] < arr[right] and arr[right] > arr[right + 1] : right+=1 elif arr[right - 1] > arr[right] and arr[right] < arr[right + 1] : right+=1 else : # If it is not satisfied, [left,right+1] cannot form a turbulence subarray. Move left to right directly left = right ret = max(ret, right - left + 1) return ret
java:
// 1. Dynamic planning class Solution { public int maxTurbulenceSize(int[] arr) { int res = 1, up = 1, down = 1; for (int i = 1; i < arr.length; i++) { if (arr[i - 1] < arr[i]) { up = down + 1; down = 1; } else if (arr[i - 1] > arr[i]) { down = up + 1; up = 1; } else { up = 1; down = 1; } res = Math.max(res, Math.max(up, down)); } return res; } } // 2. Sliding window class Solution { public int maxTurbulenceSize(int[] arr) { int n = arr.length; int ret = 1; int left = 0, right = 0; while (right < n - 1) { if (left == right) { // Special case: window length is 1 if (arr[left] == arr[left + 1]) { // When the two pointers are equal, the left and right pointers move at the same time left++; } right++; // When the two pointers are not equal, only the right pointer is moved } else { // Normal condition: the window length is not 1 // In the following two cases, you can move the right pointer to expand the window if (arr[right - 1] < arr[right] && arr[right] > arr[right + 1]) { right++; } else if (arr[right - 1] > arr[right] && arr[right] < arr[right + 1]) { right++; } else { // If it is not satisfied, [left,right+1] cannot form a turbulence subarray. Move left to right directly left = right; } } ret = Math.max(ret, right - left + 1); } return ret; } }
More links to my wonderful articles are welcome
Sorting out of thinking map of computer professional knowledge
Artificial intelligence courseware Algorithm analysis courseware Python courseware Numerical analysis courseware Machine learning courseware Image processing courseware
Sorting out the thinking map of knowledge points of postgraduate entrance examination related subjects
Knowledge points and skills of modern history in postgraduate entrance examination
The original knowledge points and skills of MA in the postgraduate entrance examination
Mathematics course notes for postgraduate entrance examination Postgraduate entrance examination English course notes Memory of roots and affixes of English words in postgraduate entrance examination Postgraduate entrance examination politics course notes
Sorting of thinking map of Python related technical knowledge points
Numpy common usage all OneNote notes Organize all notes and mind maps
Pandas common usage all OneNote notes Organize all notes and mind maps
Matplotlib common usage all OneNote notes Organize all notes and mind maps
PyTorch common usage all OneNote notes Organize all notes and mind maps
Scikit learn common usage all OneNote notes Organize all notes and mind maps
All notes on Java related technologies / ssm framework
Technology related Xiaomi mobile phone
Release time and price of Xiaomi Hongmi mobile phone models
Various series division and characteristics of common mobile phone brands
The performance of CPU s and GPU s of past dynasties and the meaning of common suffixes