Monotonic Array Java Solution

LeetCode Practice - 896. Monotonic Array 🔷Logic Behind “Monotonic Array” (Java) ✔An array is called monotonic if it moves in only one direction: 📌Either it never decreases (increasing or equal) 📌Or it never increases (decreasing or equal) ✔So the idea is very simple: 📌Check if the array follows at least one of these directions. 🔍 Step 1 — Use two flags We take two boolean variables: boolean increasing = true; boolean decreasing = true; 🔄 Step 2 — Compare neighboring elements We loop through the array and compare every pair: What does this mean? If nums[i] > nums[i+1] → array is going down, so it cannot be increasing If nums[i] < nums[i+1] → array is going up, so it cannot be decreasing We keep eliminating possibilities. 🧪 Example 1 [1, 2, 2, 3] Comparisons: 1 ≤ 2 → ok for increasing 2 ≤ 2 → ok 2 ≤ 3 → ok No violation for increasing, so: increasing = true decreasing = false ➡ Result = true 🧪 Example 2 [1, 3, 2] Comparisons: 1 < 3 → not decreasing 3 > 2 → not increasing So: increasing = false decreasing = false ➡ Result = false ✅ Final decision ✔return increasing || decreasing; ✔If either increasing or decreasing is still true, the array is monotonic. #LeetCode #Java #CodingPractice #ProblemSolving #DSA #Array #DeveloperJourney #TechLearning

  • text

To view or add a comment, sign in

Explore content categories