Uploaded by ohanran

toy problem

advertisement
TOY PROBLEM
+
LUCID CHART
08/27/2021
Given a sequence of positive integers nums and an integer k,
return whether there is a continuous sequence of nums that
sums up to exactly k.
• Example 1:
Input: nums = [23, 5, 4, 7, 2, 11], k = 20
Output: true
Explanation: 7 + 2 + 11 = 20
• Example 2:
Input: nums = [1, 3, 5, 23, 2], k = 7
Output: false
Explanation: because no sequence in this array adds up to 7.
index
23
5
4
7
2
11
0
1
2
3
4
5
k = 20
Brute force : O(N2)
left
index
23
5
4
7
2
11
0
1
2
3
4
5
right
k = 20
left
index
23
5
4
7
2
11
0
1
2
3
4
5
right
k = 20
currSum = 0
left
index
23
5
4
7
2
11
0
1
2
3
4
5
right
k = 20
currSum = 0 23
left
index
23
5
4
7
2
11
0
1
2
3
4
5
right
k = 20
currSum = 0 23
left
index
23
5
4
7
2
11
0
1
2
3
4
5
right
k = 20
currSum = 0 23 0
left
index
23
5
4
7
2
11
0
1
2
3
4
5
right
k = 20
currSum = 0 23 0 5
left
index
23
5
4
7
2
11
0
1
2
3
4
5
right
k = 20
currSum = 0 23 0 5 9
left
index
23
5
4
7
2
11
0
1
2
3
4
5
right
k = 20
currSum = 0 23 0 5 9 16
left
index
23
5
4
7
2
11
0
1
2
3
4
5
right
k = 20
currSum = 0 23 0 5 9 16 18
left
index
23
5
4
7
2
11
0
1
2
3
4
5
right
k = 20
currSum = 0 23 0 5 9 16 18 29
left
index
23
5
4
7
2
11
0
1
2
3
4
5
right
k = 20
currSum = 0 23 0 5 9 16 18 29 24
left
index
23
5
4
7
2
11
0
1
2
3
4
5
right
k = 20
currSum = 0 23 0 5 9 16 18 29 24 20
left
index
23
5
4
7
2
11
0
1
2
3
4
5
right
k = 20
currSum = 0 23 0 5 9 16 18 29 24 20
return true
O(N)
Download