我正在使用HackerRank来提高我的红宝石技能。我正在处理数据结构-数组操作问题:https://www.hackerrank.com/challenges/crush/problem
我的解决方案排在第一位,最后一个我无法实现的所谓“正确”的解决方案被列出。我的解决方案适用于** VERY **除外的所有测试用例,由于超时而失败。我知道这是由于循环造成的,但是有人可以提供其他解决方案,并解释他们的工作原理吗?
问题的解释:
样本输入
5 3
1 2 100
2 5 100
3 4 100
#n=5 m=3, then following numbers leftIndex=1 rightIndex=3 sum=100 and so on
样本输出
200
说明
After the first update list will be 100 100 0 0 0.
After the second update list will be 100 200 100 100 100.
After the third update list will be 100 200 200 200 100.
The required answer will be 200.
OR
说明为什么底部解决方案可以不循环地工作?
#Problem Data Set, my solution times out for the listed data set
10000000 100000
[
[1400906,9889280,90378],
[6581237,9872072,87106],
[4386373,9779851,52422],
[198648,4373818,5289]
]
# For this problem, variables will look like:
n = 10000000
m = 100000
q = [[1400906,9889280,90378],[6581237,9872072,87106],[4386373,9779851,52422],[198648,4373818,5289]]
def arrayManipulation(n, q)
arr = Array.new(n,0)
max = 0
q.size.times do |i|
left, right, value = q[i][0],q[i][1],q[i][2]
left -= 1
(left...right).each do |j|
arr[j] += value
max = arr[j] if max < arr[j]
end
end
return max
end
# this times out on HackerRank, please explain better solution,
#or why the bottom solution works!
result = arrayManipulation n, queries
讨论板上的工作解决方案
N, M = gets.chomp.split(' ').map(&:to_i)
# create array of zeros of length N + 1
arr = Array.new(N + 1, 0)
M.times do
# cycle through and get the inputs
start, finish, value = gets.chomp.split(' ').map(&:to_i)
# increment value at start of sequence
arr[start - 1] += value
# decrement value at first position after sequence
arr[finish] -= value
end
tmp = 0
max = 0
arr.each do |value|
# step through summing array
tmp += value
# capture the max value of tmp
max = tmp if max < tmp
end
puts max
答案 0 :(得分:4)
您的代码为O(m * n)
,因为您有一个嵌套循环来更新每个条目的数组。
工作代码为O(m + n)
:它从来没有真正存储过数组,它存储了增量数组,即可以重新构造数组的更改数组。在您的第一个示例中,它将存储:
0 0 0 0 0 0
+100 0 -100 0 0 0
+100 +100 -100 0 0 -100
+100 +100 0 0 -100 -100
这仅需要一个m
迭代的循环,而无需嵌套循环;那么您需要另一个n
迭代循环来遍历数组,保持总计运行,并确定其最大值。