@@ -38,32 +38,31 @@ object Solution {
38
38
val sz = nums.length
39
39
// We set tmp to 1 so it won't break on the first iteration
40
40
var tmp = 1
41
+ var result = true // Variable to store the result
41
42
42
- for (i <- 0 until sz) {
43
+ for (i <- 0 until sz if result ) {
43
44
// We always deduct tmp for every iteration
44
45
tmp -= 1
45
46
if (tmp < 0 ) {
46
47
// If from the previous iteration tmp is already 0, it will be < 0 here,
47
48
// leading to a false value
48
- return false
49
- }
50
- // We get the maximum value because this value is supposed to be our iterator. If both values are 0,
51
- // then the next iteration will return false.
52
- // We can stop the whole iteration with this condition. Without this condition, the code runs in 2ms (79.6%).
53
- // Adding this condition improves the performance to 1ms (100%)
54
- // because if the test case jump value is quite large, instead of just iterating, we can
55
- // just check using this condition.
56
- // Example: [10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> we can just jump to the end without iterating the whole array.
57
- tmp = math.max(tmp, nums(i))
58
- if (i + tmp >= sz - 1 ) {
59
- return true
49
+ result = false
50
+ } else {
51
+ // We get the maximum value because this value is supposed to be our iterator. If both values are 0,
52
+ // then the next iteration will return false.
53
+ // We can stop the whole iteration with this condition. Without this condition, the code runs in 2ms (79.6%).
54
+ // Adding this condition improves the performance to 1ms (100%)
55
+ // because if the test case jump value is quite large, instead of just iterating, we can
56
+ // just check using this condition.
57
+ // Example: [10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] -> we can just jump to the end without iterating the whole array.
58
+ tmp = math.max(tmp, nums(i))
59
+ if (i + tmp >= sz - 1 ) {
60
+ result = true
61
+ }
60
62
}
61
63
}
62
- // We can just return true at the end because if tmp is 0 on the previous
63
- // iteration,
64
- // even though the next iteration's index is the last one, it will return false under the
65
- // tmp < 0 condition.
66
- true
64
+
65
+ result
67
66
}
68
67
}
69
68
```
0 commit comments