Skip to content

Commit 0125d67

Browse files
feat(shortest-sublist-threshold): add shortest sublist over threshold challenge
1 parent b8d37e6 commit 0125d67

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""
2+
Given a list of positive numbers and a threshold.
3+
Find the shortest sub list which sum up to greater than the threshold
4+
"""
5+
6+
7+
def shortestThreshold(nums, threshold):
8+
if not nums:
9+
return []
10+
11+
left = right = 0
12+
current = 0
13+
minList = (float('inf'), -1, -1)
14+
15+
while right < len(nums):
16+
current += nums[right]
17+
18+
while current >= threshold and left <= right:
19+
if right - left + 1 < minList[0]:
20+
minList = (right - left + 1, left, right + 1)
21+
22+
current -= nums[left]
23+
left += 1
24+
25+
right += 1
26+
27+
while current >= threshold and left < right:
28+
if right - left < minList[0]:
29+
minList = (right - left, left, right)
30+
31+
current -= nums[left]
32+
left += 1
33+
34+
return nums[minList[1]:minList[2]]
35+
36+
37+
print(shortestThreshold([3, 5, 2], 10))
38+
print(shortestThreshold([4, 1, 3, 5, 2, 1, 8], 10))
39+
print(shortestThreshold([3, 5, 2, 1, 9], 10))
40+
print(shortestThreshold([9, 1, 3, 5, 2], 10))
41+
print(shortestThreshold([3, 5, 1, 9, 10], 10))
42+
print(shortestThreshold([3, 5, 10, 1, 9], 10))
43+
print(shortestThreshold([10, 3, 5, 1, 9], 10))

0 commit comments

Comments
 (0)