From 9530df3251eeadb4298eed789fed5a7893e96d60 Mon Sep 17 00:00:00 2001 From: ductnn Date: Sun, 15 Sep 2024 00:49:27 +0700 Subject: [PATCH] add sol --- .../sol.go | 40 +++++++++++++++++++ .../sol.py | 20 ++++++++++ 2 files changed, 60 insertions(+) create mode 100644 leetcode/2419.LongestSubarrayWithMaximumBitwiseAND/sol.go create mode 100644 leetcode/2419.LongestSubarrayWithMaximumBitwiseAND/sol.py diff --git a/leetcode/2419.LongestSubarrayWithMaximumBitwiseAND/sol.go b/leetcode/2419.LongestSubarrayWithMaximumBitwiseAND/sol.go new file mode 100644 index 0000000..c699168 --- /dev/null +++ b/leetcode/2419.LongestSubarrayWithMaximumBitwiseAND/sol.go @@ -0,0 +1,40 @@ +// https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and/description/ + +package main + +import ( + "fmt" +) + +func longestSubarray(nums []int) int { + // Step 1: Find the maximum value in the array + maxVal := nums[0] + for _, num := range nums { + if num > maxVal { + maxVal = num + } + } + + // Step 2: Find the length of the longest subarray where all elements equal maxVal + longest := 0 + currentLength := 0 + + for _, num := range nums { + if num == maxVal { + currentLength++ + if currentLength > longest { + longest = currentLength + } + } else { + currentLength = 0 + } + } + + return longest +} + +func main() { + nums := []int{1, 2, 3, 3, 2, 2, 3} + + fmt.Println(longestSubarray(nums)) +} diff --git a/leetcode/2419.LongestSubarrayWithMaximumBitwiseAND/sol.py b/leetcode/2419.LongestSubarrayWithMaximumBitwiseAND/sol.py new file mode 100644 index 0000000..b8e8e73 --- /dev/null +++ b/leetcode/2419.LongestSubarrayWithMaximumBitwiseAND/sol.py @@ -0,0 +1,20 @@ +def longestSubarray(nums): + max_val = max(nums) + + longest = 0 + current_length = 0 + + for num in nums: + if num == max_val: + current_length += 1 + longest = max(longest, current_length) + else: + current_length = 0 + + return longest + +if __name__ == "__main__": + nums = [1, 2, 3, 3, 2, 2, 3] + + result = longestSubarray(nums) + print(result)