-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path03_waysToSplitArray.py
More file actions
32 lines (32 loc) · 1.33 KB
/
03_waysToSplitArray.py
File metadata and controls
32 lines (32 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
'''Time Complexity O(n)
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.'''
from typing import *
class Solution:
def waysToSplitArray(self, nums: List[int]) -> int:
total=0
preFix=0
ans=0
for i in nums:
total+=i
for i in range(len(nums)-1):
preFix+=nums[i]
total=total-nums[i]
if preFix>=total:
ans+=1
return ans