[LeetCode] 2401. Longest Nice Subarray (Python)

2025. 3. 18. 21:36·알고리즘/LeetCode

 

 

난이도: Medium

Problem Description


You are given an array nums consisting of positive integers.

 

We call a subarray of nums nice if the bitwise AND of every pair of elements that are in different positions in the subarray is equal to 0.

 

Return the length of the longest nice subarray.

 

A subarray is a contiguous part of an array.

 

Note that subarrays of length 1 are always considered nice.

 

 

Problem Example


Example 1:

Input: nums = [1,3,8,48,10]
Output: 3
Explanation: The longest nice subarray is [3,8,48]. This subarray satisfies the conditions:
- 3 AND 8 = 0.
- 3 AND 48 = 0.
- 8 AND 48 = 0.
It can be proven that no longer nice subarray can be obtained, so we return 3.

Example 2:

Input: nums = [3,1,5,11,13]
Output: 1
Explanation: The length of the longest nice subarray is 1. Any subarray of length 1 can be chosen.

 

 

Constraints


  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109

 

 

✏️ Solution


class Solution:
    def longestNiceSubarray(self, nums: List[int]) -> int:
        answer = 1

        for right in range(len(nums)):
            now = nums[right]
            left = right -1
            while left >= 0 and now & nums[left] == 0:
                now |= nums[left]
                left -= 1
            
            answer = max(answer, right - left)

        return answer

 

약간 bruteforce 방식으로 푼 느낌이 없지 않아 있다..

 

right를 키워가며 left를 right-1로 설정하고 left를 -1씩 하면서 nums의 요소들을 AND 연산 했을 때 0이 나오지는 지 확인했다.

 

즉, 현재까지의 부분 배열 내 모든 숫자와 새로 추가된 숫자가 비트적으로 겹치지 않는지 검사하였다.

 

만약 AND 연산 시 값이 0이 아니면 반복문을 종료하고 max(answer, right-left)를 통해 최대 길이를 구할 수 있었다.

 

 

⚙️ Runtime & Memory


 

 


문제: 2401. Longest Nice Subarray

 

깃허브: github

 

algorithmPractice/LeetCode/2478-longest-nice-subarray at main · laewonJeong/algorithmPractice

하루 한 문제 챌린지. Contribute to laewonJeong/algorithmPractice development by creating an account on GitHub.

github.com

 

'알고리즘 > LeetCode' 카테고리의 다른 글

[LeetCode] 1976. Number of Ways to Arrive at Destination (Python)  (0) 2025.03.23
[LeetCode] 3108. Minimum Cost Walk in Weighted Graph (Python)  (0) 2025.03.20
[LeetCode] 2206. Divide Array Into Equal Pairs (Python)  (0) 2025.03.17
[LeetCode] 2594. Minimum Time to Repair Cars (Python)  (0) 2025.03.16
[LeetCode] 2226. Maximum Candies Allocated to K Children (Python)  (0) 2025.03.14
'알고리즘/LeetCode' 카테고리의 다른 글
  • [LeetCode] 1976. Number of Ways to Arrive at Destination (Python)
  • [LeetCode] 3108. Minimum Cost Walk in Weighted Graph (Python)
  • [LeetCode] 2206. Divide Array Into Equal Pairs (Python)
  • [LeetCode] 2594. Minimum Time to Repair Cars (Python)
Laewon Jeong
Laewon Jeong
  • Laewon Jeong
    래원
    Laewon Jeong
    글쓰기 | 관리
  • GitHub

    • github.com/laewonJeong
  • 전체
    오늘
    어제
    • 분류 전체보기 (172)
      • Docker 및 Kubernetes (11)
        • Docker (5)
        • Kubernetes (6)
      • Data Engineering (18)
        • Hadoop (5)
        • Spark (5)
        • Kafka (5)
        • Airflow (3)
      • CI|CD (3)
      • 알고리즘 (136)
        • 알고리즘 (2)
        • LeetCode (118)
        • 프로그래머스 (11)
        • BOJ (1)
        • 코딩테스트 대비 (4)
      • 서버 (2)
        • 미니 서버 (2)
      • 잡담 (1)
  • 태그

    아파치 하둡
    티스토리챌린지
    docker
    쿠버네티스
    백트래킹
    Kubernetes
    오블완
    누적합
    분산처리
    아파치 스파크
    도커
    BFS
    String
    분산
    heapq
    programmers
    leetcode
    그래프
    DP
    프로그래머스
    이진탐색
    dfs
    문자열
    코딩테스트
    우선순위큐
    Apache Spark
    Python
    파이썬
    알고리즘
    리트코드
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Laewon Jeong
[LeetCode] 2401. Longest Nice Subarray (Python)
상단으로

티스토리툴바