w3resource

Scala Programming: Find contiguous subarray within a given array of integers which has the largest sum

Scala Programming Array Exercise-39 with Solution

Write a Scala program to find contiguous subarray within a given array of integers which has the largest sum.

In computer science, the maximum sum subarray problem is the task of finding a contiguous subarray with the largest sum, within a given one-dimensional array A[1...n] of numbers. Formally, the task is to find indices and with, such that the sum is as large as possible.

Example:
Input:
int[] A = {1, 2, -3, -4, 0, 6, 7, 8, 9}
Output:
The largest sum of contiguous sub-array: 30

Sample Solution:

Scala Code:

object Scala_Array {
  def largest_sum(nums: Array[Int]): Int = {
    var max_ele_val = 0;
		var max_end = 0;
		for (i <- 0 to nums.length-1)
		{
			max_end = max_end + nums(i);
			max_end = Integer.max(max_end, 0);

			max_ele_val = Integer.max(max_ele_val, max_end);
		}
		max_ele_val;
  }
  def main(args: Array[String]): Unit = {
    val nums = Array(1, 2, -3, -4, 0, 6, 7, 8, 9);
    println("Original array:")
    for (x <- nums) {
      print(s"${x}, ")
    }
    println( s"\nThe largest sum of contiguous sub-array: ${largest_sum(nums)}" )
  }
}

Sample Output:

Original array:
1, 2, -3, -4, 0, 6, 7, 8, 9, 
The largest sum of contiguous sub-array: 30

Scala Code Editor :

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

Previous: 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.
Next: Write a Scala program to find minimum subarray sum of specified size in a given array of integers.

What is the difficulty level of this exercise?