From 6ac21f7f130ba869360d37a5c3fe75a09b809983 Mon Sep 17 00:00:00 2001 From: georgescutelnicu Date: Sun, 26 Jan 2025 14:54:39 +0200 Subject: [PATCH] Create: 0978-longest-turbulent-subarray.java --- java/0978-longest-turbulent-subarray.java | 31 +++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 java/0978-longest-turbulent-subarray.java diff --git a/java/0978-longest-turbulent-subarray.java b/java/0978-longest-turbulent-subarray.java new file mode 100644 index 000000000..109ac74e9 --- /dev/null +++ b/java/0978-longest-turbulent-subarray.java @@ -0,0 +1,31 @@ +class Solution { + public int maxTurbulenceSize(int[] arr) { + int res = 1, total = 1; + Boolean isHigher = null; + + for (int i = 1; i < arr.length; i++) { + if (arr[i] > arr[i - 1]) { + if (isHigher != null && !isHigher) { + total += 1; + } else { + total = 2; + } + isHigher = true; + } else if (arr[i] < arr[i - 1]) { + if (isHigher != null && isHigher) { + total += 1; + } else { + total = 2; + } + isHigher = false; + } else { + total = 1; + isHigher = null; + } + + res = Math.max(res, total); + } + + return res; + } +} \ No newline at end of file