w3resource

Scala Programming: Find maximum difference between two elements in a given array of integers such that smaller element appears before larger element

Scala Programming Array Exercise-38 with Solution

Write a Scala program to find maximum difference between two elements in a given array of integers such that smaller element appears before larger element.

Example:
Input:
nums = { 2, 3, 1, 7, 9, 5, 11, 3, 5 }
Output:
The maximum difference between two elements of the said array elements
10

Sample Solution:

Scala Code:

object Scala_Array {
  def diff_between_two_elemnts(nums: Array[Int]): Int = {
    var diff_two_elemnts = Integer.MIN_VALUE;
    for (i <- 0 to nums.length - 1) {
      for (j <- i + 1 to nums.length - 1) {
        diff_two_elemnts = Integer.max(diff_two_elemnts, nums(j) - nums(i));
      }
    }
    return diff_two_elemnts;
  }
  def main(args: Array[String]): Unit = {
    val nums = Array(2, 3, 1, 7, 9, 5, 11, 3, 5);
    println("Original array:")
    for (x <- nums) {
      print(s"${x}, ")
    }
    System.out.print(
      s"\nThe maximum difference between two elements of the said array elements: ${diff_between_two_elemnts(nums)}"
    )
  }
}

Sample Output:

Original array:
2, 3, 1, 7, 9, 5, 11, 3, 5, 
The maximum difference between two elements of the said array elements: 10

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: 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.
Next: Write a Scala program to find contiguous subarray within a given array of integers which has the largest sum.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://www.w3resource.com/scala-exercises/array/scala-array-exercise-38.php