It can be done in O(n) time by using Kadane's algorithm.
https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/