We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
One insight that might help is that we're keeping track of the change in values rather than the values themselves at each index. Therefore, by adding the k at a and subtracting it after b, we are saying that at a the total value increases by k compared to the previous element, and after b the total value decreases by k compared to b. Hope that helps!
Here's the same solution in swift in case anyone needs it :).
func arrayManipulation(n: Int, queries: [[Int]]) -> Int {
var sums = Int: Int
for query in queries {
sums[query[0]] = (sums[query[0]] ?? 0) + query[2]
sums[query[1] + 1] = (sums[query[1] + 1] ?? 0) - query[2]
}
var currentmax = 0
var sum = 0
sums.sorted{ `$0.0 < $`1.0 }.
compactMap{ `$0.1; sum += $`0.1; currentmax = sum > currentmax ? sum : currentmax}
return currentmax
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Join us
Create a HackerRank account
Be part of a 26 million-strong community of developers
Please signup or login in order to view this challenge
Array Manipulation
You are viewing a single comment's thread. Return to all comments →
One insight that might help is that we're keeping track of the change in values rather than the values themselves at each index. Therefore, by adding the k at a and subtracting it after b, we are saying that at a the total value increases by k compared to the previous element, and after b the total value decreases by k compared to b. Hope that helps!
Here's the same solution in swift in case anyone needs it :).
func arrayManipulation(n: Int, queries: [[Int]]) -> Int { var sums = Int: Int for query in queries { sums[query[0]] = (sums[query[0]] ?? 0) + query[2] sums[query[1] + 1] = (sums[query[1] + 1] ?? 0) - query[2] }
}