16 October 2014

Quiz 39: Find index of flowers

Problem:
Mohit wants to buy 2 flowers for pooja. He have m rupees and flower shop have n different flowers. Given price of each flower, find the indexes of 2 flowers such that all the money Mohit have is used.

Input Format: 
m = money
n = number of different flowers
cost of n flowers separated by space.

Output Format: 
index1 index2

Constraints: 
none

Sample Input
200
10
1 5 15 25 198 14 200 2 100 150

Sample Output:
5 8

Explanations:
198+2=200, index of 198 is 5 and index of 2 is 8


Solution:

chomp($m=<STDIN>);
chomp($n=<STDIN>);
chomp($l=<STDIN>);
@list=split(/ /,$l);
for($j=0;$j<$n;$j++)
{
for($k=$j+1;$k<$n;$k++)
{
if($m == $list[$j]+$list[$k])
{
print $j+1;
print " ";
print $k+1;
last;
}
}
}



Tips:
Use last to end the loop as soon as your job is done

No comments:

Post a Comment