HackerRank Stock Maximize
提出
11/12 test cases failed :(
code: python
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
else:
stock = 0
return money + stock*prices-1 if __name__ == '__main__':
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
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
# 2
# 100
# 2
m = prices.pop()
maxsum = 0
arrsum = 0
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__':
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()
メモ