Skip to content

Commit

Permalink
Merge pull request #74 from arunsathiya/solve/2366-minimum-replacemen…
Browse files Browse the repository at this point in the history
…ts-to-sort-the-array

2366. Minimum Replacements To Sort The Array
  • Loading branch information
arunsathiya committed Feb 26, 2024
2 parents 979910a + f89902a commit e0ce631
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/2366-minimum-replacements-to-sort-the-array/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package main

func minimumReplacement(nums []int) int64 {
count := 0
for i := len(nums) - 1; i > 0; i-- {
current := nums[i]
prev := nums[i-1]
if prev <= current {
continue
}
operationsNeeded := (prev + current - 1) / current
count += operationsNeeded - 1
nums[i-1] = prev / operationsNeeded
}
return int64(count)
}
35 changes: 35 additions & 0 deletions src/2366-minimum-replacements-to-sort-the-array/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package main

import "testing"

func TestMinimumReplacement(t *testing.T) {
tests := []struct {
name string
nums []int
want int64
}{
{
name: "Example 1",
nums: []int{3, 9, 3},
want: 2,
},
{
name: "Example 2",
nums: []int{1, 2, 3, 4, 5},
want: 0,
},
{
name: "Example 3",
nums: []int{12, 9, 7, 6, 17, 19, 21},
want: 6,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := minimumReplacement(tt.nums); got != tt.want {
t.Errorf("minimumReplacement() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit e0ce631

Please sign in to comment.