Write a Scala program to find contiguous subarray within a given array of integers which has the largest sum.
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
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
Sample Output:
need an explanation for this answer? contact us directly to get an explanation for this answer