HackerRank Stock Maximize
https://www.hackerrank.com/challenges/stockmax/problem
提出
11/12 test cases failed :(
code: python
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'stockmax' function below.
#
# The function is expected to return a LONG_INTEGER.
# The function accepts INTEGER_ARRAY prices as parameter.
#
def stockmax(prices):
# Write your code here
money = 0
stock = 0
for i in range(len(prices)-1):
if (pricesi+1 > pricesi):
stock += 1
money -= pricesi
else:
money += stock * pricesi
stock = 0
return money + stock*prices-1
if __name__ == '__main__':
fptr = open(os.environ'OUTPUT_PATH', 'w')
t = int(input().strip())
for t_itr in range(t):
n = int(input().strip())
prices = list(map(int, input().rstrip().split()))
result = stockmax(prices)
fptr.write(str(result) + '\n')
fptr.close()
解答
code: python
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'stockmax' function below.
#
# The function is expected to return a LONG_INTEGER.
# The function accepts INTEGER_ARRAY prices as parameter.
#
def stockmax(prices):
# Write your code here
# 1, 3, 1, 2
# 1, 2, 100
# 5, 3, 2
# 2
# 100
# 2
m = prices.pop()
maxsum = 0
arrsum = 0
# 1, 3, 1
# 1, 2
# 3, 5
for p in reversed(prices):
m = max(m, p)
# 2, 3, 3
# 100, 100
# 3, 5
maxsum+=m # maximum future price(reverse)
# 1, 3, 1
# 1, 2
# 3, 5
arrsum+=p # current price
return maxsum - arrsum
if __name__ == '__main__':
fptr = open(os.environ'OUTPUT_PATH', 'w')
t = int(input().strip())
for t_itr in range(t):
n = int(input().strip())
prices = list(map(int, input().rstrip().split()))
result = stockmax(prices)
fptr.write(str(result) + '\n')
fptr.close()
メモ
Hackerrank - Stock Maximize Solution