문제 링크 -https://www.hackerrank.com/challenges/crush/problem
Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in your array.
For example, the length of your array of zeros . Your list of queries is as follows:
a b k 1 5 3 4 8 7 6 9 1
Add the values of between the indices and inclusive:
index->
1 2 3 4 5 6 7 8 9 10
[0,0,0, 0, 0,0,0,0,0, 0]
[3,3,3, 3, 3,0,0,0,0, 0]
[3,3,3,10,10,7,7,7,0, 0]
[3,3,3,10,10,8,8,8,1, 0]
The largest value is after all operations are performed.
Function Description
Complete the function arrayManipulation in the editor below. It must return an integer, the maximum value in the resulting array.
arrayManipulation has the following parameters:
- n - the number of elements in your array
- queries - a two dimensional array of queries where each queries[i] contains three integers, a, b, and k.
Input Format
The first line contains two space-separated integers and , the size of the array and the number of operations.
Each of the next lines contains three space-separated integers , and , the left index, right index and summand.
Constraints
- 3 <= n <= 10^7
- 1 <= m <= 2 *10 ^5
- 1 <= a <= b <=n
- 0 <= k <= 10^9
Output Format
Return the integer maximum value in the finished array.
Sample Input
5 3
1 2 100
2 5 100
3 4 100
Sample Output
200
Explanation
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 .
풀이 1
golang이 편해 golang 으로 테스트를 진행 했다.
var a []int64
a = []int64{}
var res int64
res = 0
for i := 0; i < len(queries) ; i++{
for j := queries[i][0] ; j <= queries[i][1] ; j++{
a[j-1] += int64(queries[i][2])
}
}
for k :=0 ; k< len(a) ; k++{
fmt.Println(a[k])
if a[k] > res {
res = a[k]
}
}
위의 풀이로는 복잡도가 O(n)*O(n) 으로 샘플테스트는 통과하나 실제 테스트케이스는 40프로 정도 런타임 오류로 통과하지 못한다.
복잡도를 줄여야한다.
풀이 2
아래와 같은 풀이법으로 다른 분이 파이썬으로 개발 해놓은것을 go로 옮겨서 테스트 해봤더니 모든 테스트 케이스 통과
func arrayManipulation(n int32, queries [][]int32) int64 {
res := int64(-1)
var result = make([]int64, n+1)
for _, a := range queries{
start := int64(a[0] -1)
end := int64(a[1])
result[start] += int64(a[2])
result[end] += int64(-a[2])
}
tmp := int64(0)
for _,a := range result{
tmp += a
if res < tmp{
res = tmp
}
}
return res
}
1. 주어진 n보다 하나 큰 슬라이스(result)를 만든다.
2. start 에 a-1 , end에 b를 넣는다
3. result[start], result[end] 에 각각 k, -k를 넣는다
4. result 를 for돌며 더하다가 가장 큰수를 res에 넣고 반환한다.
복잡도는 O(n)로 모든 테스트 케이스 통과
** start와 end사이에 k만큼 더해져있으니 차례로 돌면서 확인할 때 k만큼 있다고 명시 해놓는듯