priceIsRight

Category: Arrays
Author: Victoria Kirst
Book Chapter: 7.2
Problem: priceIsRight
Write a method priceIsRight which takes an array of integers bids and an integer price as parameters. The
method returns the element in the bids array that is closest in value to price without being larger than price. For
example, if bids stores the elements {200, 300, 250, 999, 40}, then priceIsRight(bids, 280) should
return 250, since 250 is the bid closest to 280 without going over 280. If all bids are larger than price, then your
method should return -1.
The following table shows some calls to your method and their expected results:
Arrays
int[]
int[]
int[]
int[]
int[]
a1
a2
a3
a4
a5
=
=
=
=
=
{234, 528, 235, 253, 400};
{98, 70, 72};
{900, 885, 989, 1};
{200};
{500, 300, 241, 99, 501};
Returned Value
300) returns 253
72) returns 72
880) returns 1
120) returns 200
50) returns -1
priceIsRight(a1,
priceIsRight(a2,
priceIsRight(a3,
priceIsRight(a4,
priceIsRight(a5,
You may assume there is at least 1 element in the array, and you may assume that the price and the values in bids will
all be greater than or equal to 1. Do not modify the contents of the array passed to your method as a parameter.