Member-only story
Solution to Leetcode problem 978 Longest Turbulent Subarray
This post is the Java solution for Leet code problem 978. In this exercise, a turbulence is defined as being the sequence of successive strict increases and decreases.
For this problem, my approach was to go through the array greedily and remember the current turbulence as well as the longest turbulence seen.
In the details, there are a few edge cases that we need to take care of. The case of 2 equal elements following each other in the array is distinct from the end of a turbulence where where elements are not equal. For instance with the sequence 1,2,2,...
contains a turbulence of size 2 [1,2]
end the next turbulence starts with the second appearance of the element 2 (A[2]
) , whereas 1,2,3,...
contains a turbulence of size 2 [1,2]
end the next turbulence starts with the 2 elements 2,3
. In other words, the following turbulence starts with a size one in the equal case, and starts with a size 2 in the non equal case.
I also wondered the best way to start, given that only one element was guaranteed in the array. Then I special cased the times when the current turbulence was of size 1
, because in that case there was no direction that was imposed for the next element, it was only required that it was not equal to the previous element.