Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now