[LeetCode] 2270. Number of Ways to Split Array (Python)

2025. 1. 3. 23:40·알고리즘/LeetCode

 

난이도: Medium

 

문제 설명


You are given a 0-indexed integer array nums of length n.

nums contains a valid split at index i if the following are true:

  • The sum of the first i + 1 elements is greater than or equal to the sum of the last n - i - 1 elements.
  • There is at least one element to the right of i. That is, 0 <= i < n - 1.

Return the number of valid splits in nums.

 

문제 예제


Example 1:

Input: nums = [10,4,-8,7]
Output: 2
Explanation: 
There are three ways of splitting nums into two non-empty parts:

- Split nums at index 0. Then, the first part is [10], and its sum is 10. The second part is [4,-8,7], and its sum is 3. Since 10 >= 3, i = 0 is a valid split.
- Split nums at index 1. Then, the first part is [10,4], and its sum is 14. The second part is [-8,7], and its sum is -1. Since 14 >= -1, i = 1 is a valid split.
- Split nums at index 2. Then, the first part is [10,4,-8], and its sum is 6. The second part is [7], and its sum is 7. Since 6 < 7, i = 2 is not a valid split.
Thus, the number of valid splits in nums is 2.

Example 2:

Input: nums = [2,3,1,0]
Output: 2
Explanation: 
There are two valid splits in nums:

- Split nums at index 1. Then, the first part is [2,3], and its sum is 5. The second part is [1,0], and its sum is 1. Since 5 >= 1, i = 1 is a valid split. 
- Split nums at index 2. Then, the first part is [2,3,1], and its sum is 6. The second part is [0], and its sum is 0. Since 6 >= 0, i = 2 is a valid split.

 

제한 사항


  • 2 <= nums.length <= 10^5
  • -105 <= nums[i] <= 10^5

 

✏️ Solution(솔루션)


class Solution:
    def waysToSplitArray(self, nums: List[int]) -> int:
        n = len(nums)
        answer = 0
        prefix = [0 for _ in range(n)]
        suffix = [0 for _ in range(n)]

        prefix[0] = nums[0]
        suffix[-1] = nums[-1]

        for i in range(1, n):
            prefix[i] = prefix[i-1] + nums[i]
        
        for i in range(n-2, -1, -1):
            suffix[i] = suffix[i+1] + nums[i]

        for i in range(n-1):
            if prefix[i] >= suffix[i+1]:
                answer += 1
        
        return answer

 

먼저 prefix와 suffix 라는 리스트를 만들었다.

 

prefix는 누적합을 저장하는 리스트이다.

ex) Input: [10, 4, -8, 7] ==> prefix = [10, 14, 6, 13]

 

suffix는 배열의 끝에서부터 누적합을 저장하는 리스트이다.

ex) Input: [10, 4, -8, 7] ==> suffix = [13 ,3,-1, 7]

 

prefix와 suffix 리스트가 모두 저장 완료되면 n-1번 도는 for문을 선언했다.

각 반복마다 prefix[i]와 suffix[i+1]을 비교하여 조건을 만족하면 answer를 +1 해주었다.

 

마지막으로 answer를 return하여 정답을 맞출 수 있었다.


문제: 2270. Number of Ways to Split Array

깃허브: github

 

algorithm_practice/LeetCode/2358-number-of-ways-to-split-array at main · laewonJeong/algorithm_practice

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

github.com

 

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

[LeetCode] 2381. Shifting Letters II (Python)  (0) 2025.01.05
[LeetCode] 1930. Unique Length-3 Palindromic Subsequences (Python)  (1) 2025.01.04
[LeetCode] 2559. Count Vowel Strings in Ranges (Python)  (1) 2025.01.02
[LeetCode] 1422. Maximum Score After Splitting a String (Python)  (0) 2025.01.02
[LeetCode] 322. Coin Change (Python)  (0) 2024.12.31
'알고리즘/LeetCode' 카테고리의 다른 글
  • [LeetCode] 2381. Shifting Letters II (Python)
  • [LeetCode] 1930. Unique Length-3 Palindromic Subsequences (Python)
  • [LeetCode] 2559. Count Vowel Strings in Ranges (Python)
  • [LeetCode] 1422. Maximum Score After Splitting a String (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)
  • 태그

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

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Laewon Jeong
[LeetCode] 2270. Number of Ways to Split Array (Python)
상단으로

티스토리툴바