forked from Kyrylo-Ktl/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sum of Even Numbers After Queries.py
74 lines (54 loc) · 1.72 KB
/
Sum of Even Numbers After Queries.py
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
from typing import List
class Solution:
"""
Time: O(n + m)
Memory: O(1)
"""
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
even_sum = sum(num for num in nums if not num & 1)
sums = []
for val, i in queries:
if val & 1 and nums[i] & 1:
even_sum += nums[i] + val
elif val & 1 and not nums[i] & 1:
even_sum += -nums[i]
elif not val & 1 and not nums[i] & 1:
even_sum += val
nums[i] += val
sums.append(even_sum)
return sums
class Solution:
"""
Time: O(n + m)
Memory: O(1)
"""
CHANGE = {
( True, True): lambda val, diff: val + diff,
( True, False): lambda val, diff: 0,
(False, True): lambda val, diff: -val,
(False, False): lambda val, diff: diff,
}
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
even_sum = sum(num for num in nums if not num & 1)
sums = []
for val, i in queries:
even_sum += self.CHANGE[nums[i] & 1, val & 1](nums[i], val)
sums.append(even_sum)
nums[i] += val
return sums
class Solution:
"""
Time: O(n + m)
Memory: O(1)
"""
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
even_sum = sum(num for num in nums if not num & 1)
sums = []
for val, i in queries:
if not nums[i] & 1:
even_sum -= nums[i]
nums[i] += val
if not nums[i] & 1:
even_sum += nums[i]
sums.append(even_sum)
return sums