Skip to content

Commit 9530df3

Browse files
committed
add sol
1 parent 18b4036 commit 9530df3

File tree

2 files changed

+60
-0
lines changed
  • leetcode/2419.LongestSubarrayWithMaximumBitwiseAND

2 files changed

+60
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and/description/
2+
3+
package main
4+
5+
import (
6+
"fmt"
7+
)
8+
9+
func longestSubarray(nums []int) int {
10+
// Step 1: Find the maximum value in the array
11+
maxVal := nums[0]
12+
for _, num := range nums {
13+
if num > maxVal {
14+
maxVal = num
15+
}
16+
}
17+
18+
// Step 2: Find the length of the longest subarray where all elements equal maxVal
19+
longest := 0
20+
currentLength := 0
21+
22+
for _, num := range nums {
23+
if num == maxVal {
24+
currentLength++
25+
if currentLength > longest {
26+
longest = currentLength
27+
}
28+
} else {
29+
currentLength = 0
30+
}
31+
}
32+
33+
return longest
34+
}
35+
36+
func main() {
37+
nums := []int{1, 2, 3, 3, 2, 2, 3}
38+
39+
fmt.Println(longestSubarray(nums))
40+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
def longestSubarray(nums):
2+
max_val = max(nums)
3+
4+
longest = 0
5+
current_length = 0
6+
7+
for num in nums:
8+
if num == max_val:
9+
current_length += 1
10+
longest = max(longest, current_length)
11+
else:
12+
current_length = 0
13+
14+
return longest
15+
16+
if __name__ == "__main__":
17+
nums = [1, 2, 3, 3, 2, 2, 3]
18+
19+
result = longestSubarray(nums)
20+
print(result)

0 commit comments

Comments
 (0)