LeetCode 75
Longest Subarray With Maximum Bitwise AND
- Problem
- LC 2419
- Topic
- Bit Manipulation
- File
- official75_LC2419LongestSubarrayWithMaximumBitwiseAND.java
- Path
- pkg5leetcode/official75/official75_LC2419LongestSubarrayWithMaximumBitwiseAND.java
- Package
- pkg5leetcode.official75
- Command
- java pkg5leetcode/official75/official75_LC2419LongestSubarrayWithMaximumBitwiseAND.java
- Approach
- Track current max AND and streak of elements >= max.
- Complexity
- Time O(n), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.official75;2 3/*4 * Longest Subarray With Maximum Bitwise AND | LC 24195 * APPROACH: Track current max AND and streak of elements >= max.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class official75_LC2419LongestSubarrayWithMaximumBitwiseAND {9 static int longestSubarray(int[] nums) {10 int max = 0;11 for (int n : nums) max = Math.max(max, n);12 int best = 0, cur = 0;13 for (int n : nums) {14 if (n == max) { cur++; best = Math.max(best, cur); }15 else cur = 0;16 }17 return best;18 }19 20 public static void main(String[] args) {21 check(longestSubarray(new int[]{1,2,3,3,3,2,2}) == 3, "case1");22 check(longestSubarray(new int[]{1,2,3,4}) == 1, "case2");23 System.out.println("all tests passed");24 }25 26 static void check(boolean cond, String name) {27 if (!cond) throw new AssertionError("FAILED: " + name);28 System.out.println(" PASS " + name);29 }30}