-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy patharrayChange.R
More file actions
executable file
·59 lines (57 loc) · 1.91 KB
/
arrayChange.R
File metadata and controls
executable file
·59 lines (57 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# You are given an array of integers. On each move you are allowed to increase exactly one of its element by one. Find the minimal number of moves required to obtain a strictly increasing sequence from the input.
#
# Example
#
# For inputArray = [1, 1, 1], the output should be
# arrayChange(inputArray) = 3.
#
# Input/Output
#
# [execution time limit] 5 seconds (r)
#
# [input] array.integer inputArray
#
# Guaranteed constraints:
# 3 ≤ inputArray.length ≤ 105,
# -105 ≤ inputArray[i] ≤ 105.
#
# [output] integer
# The minimal number of moves needed to obtain a strictly increasing sequence from inputArray.
# It's guaranteed that for the given test cases the answer always fits signed 32-bit integer type.
# inputArray <- list(1,1,1)
# inputArray <- list(-1000, 0, -2, 0)
# inputArray <- list(2, 1, 10, 1)
#this solution was still not fast enough for 1 test input. :\
arrayChange <- function(inputArray) {
inputArray <- unlist(inputArray)
ArrayDiff <- diff(inputArray)
inputArrayModified <- inputArray
if (sum(ArrayDiff > 0) == length(ArrayDiff)) {
return(0)
} else {
#do it in 1 iteration
#first first dec diff
sumsteps = 0;
for (ind in seq(from = min(which(ArrayDiff <= 0)), to = length(ArrayDiff))) {
ArrayDiff <- diff(inputArray)
if (sum(ArrayDiff > 0) == length(ArrayDiff)) {
return(sumsteps)
}
if (ArrayDiff[ind] <= 0) {
stepsTomakeitPos <- (1 - (ArrayDiff[ind]))
sumsteps <- sumsteps + stepsTomakeitPos
inputArray[ind + 1] <- inputArray[ind + 1] + stepsTomakeitPos
}
}
}
return(sumsteps)
}
#someone else's solution: pretty elegant
# arrayChange <- function(inputArray) {
# inputArray <- unlist(inputArray)
# initial <- inputArray
# for (ind in 2:length(inputArray)) {
# inputArray[ind] <- max(inputArray[ind-1] + 1,inputArray[ind])
# }
# return(sum(inputArray - initial))
# }