Skip to content

Commit d1cfe53

Browse files
committed
Add Greedy
* Candies * Gas Stations * Jump To The End
1 parent 77cb109 commit d1cfe53

File tree

3 files changed

+62
-0
lines changed

3 files changed

+62
-0
lines changed

kotlin/Greedy/Candies.kt

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
fun candies(ratings: List<Int>): Int {
2+
val n = ratings.size
3+
// Ensure each child starts with 1 candy.
4+
val candies = IntArray(n) { 1 }
5+
// First pass: for each child, ensure the child has more candies
6+
// than their left-side neighbor if the current child's rating is
7+
// higher.
8+
for (i in 1 until n) {
9+
if (ratings[i] > ratings[i - 1]) {
10+
candies[i] = candies[i - 1] + 1
11+
}
12+
}
13+
// Second pass: for each child, ensure the child has more candies
14+
// than their right-side neighbor if the current child's rating is
15+
// higher.
16+
for (i in n - 2 downTo 0) {
17+
if (ratings[i] > ratings[i + 1]) {
18+
// If the current child already has more candies than their
19+
// right-side neighbor, keep the higher amount.
20+
candies[i] = maxOf(candies[i], candies[i + 1] + 1)
21+
}
22+
}
23+
return candies.sum()
24+
}

kotlin/Greedy/GasStations.kt

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
fun gasStations(gas: List<Int>, cost: List<Int>): Int {
2+
// If the total gas is less than the total cost, completing the
3+
// circuit is impossible.
4+
if (gas.sum() < cost.sum()) {
5+
return -1
6+
}
7+
var start = 0
8+
var tank = 0
9+
for (i in 0 until gas.size) {
10+
tank += gas[i] - cost[i]
11+
// If our tank has negative gas, we cannot continue through the
12+
// circuit from the current start point, nor from any station
13+
// before or including the current station 'i'.
14+
if (tank < 0) {
15+
// Set the next station as the new start point and reset the
16+
// tank.
17+
start = i + 1
18+
tank = 0
19+
}
20+
}
21+
return start
22+
}

kotlin/Greedy/JumpToTheEnd.kt

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
fun jumpToTheEnd(nums: List<Int>): Boolean {
2+
// Set the initial destination to the last index in the array.
3+
var destination = nums.size - 1
4+
// Traverse the array in reverse to see if the destination can be
5+
// reached by earlier indexes.
6+
for (i in nums.size - 2 downTo 0) {
7+
// If we can reach the destination from the current index,
8+
// set this index as the new destination.
9+
if (i + nums[i] >= destination) {
10+
destination = i
11+
}
12+
}
13+
// If the destination is index 0, we can jump to the end from index
14+
// 0.
15+
return destination == 0
16+
}

0 commit comments

Comments
 (0)