w3resource

Scala Programming: Find minimum subarray sum of specified size in a given array of integers

Scala Programming Array Exercise-40 with Solution

Write a Scala program to find minimum subarray sum of specified size in a given array of integers.

Example:
Input:
nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9,10}
Output:
Sub-array size: 4
Sub-array from 0 to 3 and sum is: 10

Sample Solution:

Scala Code:

object Scala_Array {
  def find_min_subarray_sum(nums: Array[Int], k:Int): Array[Int] = {
    var sub_arr_sum = 0;
		var min_sub_arr = Integer.MAX_VALUE;
		var last = 0;
    var result = new Array[Int](3)
		for ( i<- 0 to nums.length-1)
		{
			sub_arr_sum += nums(i);

			if (i + 1 >= k)
			{
				if (min_sub_arr > sub_arr_sum)
				{
					min_sub_arr = sub_arr_sum 
					last = i;
				}

				sub_arr_sum -= nums(i + 1 - k);
			}
		}
		result(0) = last - k + 1;
		result(1) = last;
		result(2) = min_sub_arr;
    result;
  }

  def main(args: Array[String]): Unit = {
    val nums = Array(1, 2, 3, 4, 5, 6, 7, 8, 9,10);
    println("Original array:")
    for (x <- nums) {
      print(s"${x}, ")
    }
    val k =4;
    val result = find_min_subarray_sum(nums, k);
    println(s"\nSub-array from ${result(0)} to ${result(1)} and sum is: ${result(2)}");  
  }
}

Sample Output:

Original array:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 
Sub-array from 0 to 3 and sum is: 10

Scala Code Editor :

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

Previous: 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?