Scala Programming: Find maximum product of two integers in a given array of integers
Scala Programming Array Exercise-36 with Solution
Write a Scala program to find maximum product of two integers in a given array of integers.
Example:
Input:
nums = { 2, 3, 5, 7, -7, 5, 8, -5 }
Output:
Pair is (7, 8), Maximum Product: 56
Sample Solution:
Scala Code:
object Scala_Array {
def find_max_product(nums: Array[Int]): Unit = {
var max_pair_product = Integer.MIN_VALUE;
var max_i = -1
var max_j = -1;
for ( i<- 0 to nums.length - 1)
{
for (j<- i + 1 to nums.length - 1)
{
if (max_pair_product < nums(i) * nums(j))
{
max_pair_product = nums(i) * nums(j);
max_i = i;
max_j = j;
}
}
}
println(s"\nPair is (${nums(max_i)} , ${nums(max_j)}), \nMaximum Product: ${(nums(max_i)*nums(max_j))}");
}
def main(args: Array[String]): Unit = {
val nums = Array(2, 3, 5, 7, -7, 5, 8, -5 );
println("Original array:")
for (x <- nums) {
print(s"${x}, ")
}
find_max_product(nums);
}
}
Sample Output:
Original array: 2, 3, 5, 7, -7, 5, 8, -5, Pair is (7 , 8), Maximum Product: 56
Scala Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Scala program to find all pairs of elements in an array whose sum is equal to a specified number.
Next: Write a Scala program to rearrange a given array of unique elements such that every second element of the array is greater than its left and right elements.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/scala-exercises/array/scala-array-exercise-36.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics