Problem:
Given a sequence, you have to make the sequence increasing by adding a number d any number of times. like if d is 2 and sequence is 5 1, then adding 2 for 3 times will make sequence 5 7 which is in increasing order. Number of moves for this example was 3. Find minimum number of moves required to make the sequence increasing.
Input Format:
N D(total numbers and number D to be added)
sequence(each number separated by space)Output Format:
Minimum number of movesConstraints:
NoneSample Input
6 3
1 5 2 22 21 2
1 5 2 22 21 2
Sample Output:
11Explanations:
new sequence would be 1,5,8(2+3*2),22,24(21+3*1),26(2+3*8), so total=2+1+8=11
Solution:
($n,$d)=split(" ",$line1);
chomp($line2=<STDIN>);
@arr=split(" ",$line2);
$ans=0;
for($i=0;$i<$n-1;$i++)
{
if($arr[$i]>=$arr[$i+1])
{
$dif=$arr[$i]-$arr[$i+1];
$num=int($dif/$d)+1;
$ans=$ans+$num;
$arr[$i+1]=$arr[$i+1]+($num*$d);
}
}
print $ans;
Tips:
Update array elements and continue comparing
No comments:
Post a Comment