Skip to content

Commit bfeea60

Browse files
add 413 alt sol
1 parent 762f062 commit bfeea60

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

contest/src/main/java/com/github/contest/slidingWindow/SlidingWindowAlternativeSolution.kt

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,4 +109,33 @@ fun getSubArrayBeautyAlternativeSolution(nums: IntArray, k: Int, x: Int): IntArr
109109
return res.toIntArray()
110110
}
111111

112+
/**
113+
* 413. Arithmetic Slices
114+
* Alternative Solution with O(n)
115+
*/
116+
117+
fun numberOfArithmeticSlicesAlternativeSolution(nums: IntArray): Int {
118+
if (nums.size < 3) return 0
119+
120+
var left = 0
121+
var count = 0
122+
val k = 3
123+
var diff = nums[1] - nums[0]
124+
125+
for (right in 2 until nums.size) {
126+
127+
if (nums[right] - nums[right - 1] != diff) {
128+
diff = nums[right] - nums[right - 1]
129+
left = right - 1
130+
}
131+
132+
if (right - left >= k - 1) {
133+
count++
134+
count += ((right - left) - (k - 1))
135+
}
136+
}
137+
138+
return count
139+
}
140+
112141

0 commit comments

Comments
 (0)