object MaxSumFromEnds { def maxSumFromEitherEnd(nums: Array[Int]): Int = { val n = nums.length // Initialize leftMax and rightMax arrays to store max sums from the left and right ends val leftMax = Array.fill(n)(0) val rightMax = Array.fill(n)(0) // Calculate the max sum from the left end leftMax(0) = nums(0) var maxLeft = nums(0) for (i <- 1 until n) { leftMax(i) = Math.max(nums(i), leftMax(i - 1) + nums(i)) maxLeft = Math.max(maxLeft, leftMax(i)) } // Calculate the max sum from the right end rightMax(n - 1) = nums(n - 1) var maxRight = nums(n - 1) for (i <- (n - 2) to 0 by -1) { rightMax(i) = Math.max(nums(i), rightMax(i + 1) + nums(i)) maxRight = Math.max(maxRight, rightMax(i)) } // Find the maximum sum from either end Math.max(maxLeft, maxRight) } def main(args: Array[String]): Unit = { val nums = Array(1, 2, 3, -2, 5) val maxSum = maxSumFromEitherEnd(nums) println(s"Maximum sum from either end: $maxSum") } }