2020. 3. 31. 21:20ㆍPython/CodeSignal Algorithm
37. Given array of integers, find the maximal possible sum of some of its k consecutive elements.
[Example]
For inputArray = [2, 3, 5, 1, 6] and k = 2, the output should be
|
[Soluton]
#<My Code>
def arrayMaxConsecutiveSum(inputArray, k):
a = inputArray
s = m = sum(a[:k])
for i in range(len(a) - k):
s += a[i + k] - a[i]
m = max(m, s)
return m
#<Best Code>
def arrayMaxConsecutiveSum(a, k):
c = m = sum(a[:k])
for i in range(len(a) - k):
c = c + a[i + k] - a[i]
m = max(c, m)
return m
38. Caring for a plant can be hard work, but since you tend to it regularly, you have a plant that grows consistently. Each day, its height increases by a fixed amount represented by the integer upSpeed. But due to lack of sunlight, the plant decreases in height every night, by an amount represented by downSpeed.
Since you grew the plant from a seed, it started at height 0 initially. Given an integer desiredHeight, your task is to find how many days it'll take for the plant to reach this height.
[Example]
For upSpeed = 100, downSpeed = 10, and desiredHeight = 910, the output should be
The plant first reaches a height of 910 on day 10. |
[Solution]
#<My Code>
def growingPlant(upSpeed, downSpeed, desiredHeight):
grew_height = 0
days = 0
while True:
days += 1
grew_height += upSpeed
if desiredHeight <= grew_height:
return days
grew_height -= downSpeed
#<Best Code>
def growingPlant(upSpeed, downSpeed, desiredHeight):
if desiredHeight <= upSpeed:
return 1
return math.ceil((desiredHeight - upSpeed) / (upSpeed - downSpeed) + 1)
39. You found two items in a treasure chest! The first item weighs weight1 and is worth value1, and the second item weighs weight2 and is worth value2. What is the total maximum value of the items you can take with you, assuming that your max weight capacity is maxW and you can't come back for the items later?
Note that there are only two items and you can't bring more than one item of each type, i.e. you can't take two first items or two second items.
[Example]
|
[Solution]
#<My Code>
def knapsackLight(v1, w1, v2, w2, maxW):
if maxW < (w1 + w2):
if v1 > v2 and w1 <= maxW:
return v1
elif v1 < v2 and w2 <= maxW:
return v2
elif w1 <= maxW:
return v1
elif w2 <= maxW:
return v2
else:
return 0
else:
return v1 + v2
#<Best Code>
def knapsackLight(v1, w1, v2, w2, W):
return max(int(w1<=W)*v1, int(w2<=W)*v2, int(w1+w2<=W)*(v1+v2))
'Python > CodeSignal Algorithm' 카테고리의 다른 글
[Python] CodeSignal 문제 풀이 (43~45) (0) | 2020.03.31 |
---|---|
[Python] CodeSignal 문제 풀이 (40~42) (0) | 2020.03.31 |
[Python] CodeSignal 문제 풀이 (34~36) (0) | 2020.03.31 |
[Python] CodeSignal 문제 풀이 (33~35) (0) | 2020.03.21 |
[Python] CodeSignal 문제 풀이 (31~33) (0) | 2020.03.12 |