<p>Given an integer array <code>nums</code>, find the <span data-keyword="subarray-nonempty">subarray</span> with the largest sum, and return <em>its sum</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [-2,1,-3,4,-1,2,1,-5,4]
<strong>Output:</strong> 6
<strong>Explanation:</strong> The subarray [4,-1,2,1] has the largest sum 6.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [1]
<strong>Output:</strong> 1
<strong>Explanation:</strong> The subarray [1] has the largest sum 1.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> nums = [5,4,-1,7,8]
<strong>Output:</strong> 23
<strong>Explanation:</strong> The subarray [5,4,-1,7,8] has the largest sum 23.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
</ul>

<p>&nbsp;</p>
<p><strong>Follow up:</strong> If you have figured out the <code>O(n)</code> solution, try coding another solution using the <strong>divide and conquer</strong> approach, which is more subtle.</p>

"""Given an integer array nums, find the 
subarray
 with the largest sum, and return its sum.

Subarray has no gaps

Split array into one number subarrays
Decisions:
    add num to the right
    don't add anyone
"""


class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        def iterativeSolution(nums:list[int]) -> int:
            total = 0
            bestSoFar = 0
            for i in nums:
                total += i
                if total > bestSoFar:
                    bestSoFar = total
                elif total <= 0:
                    return bestSoFar
            return bestSoFar

        best = max(nums)

        merged = True
        while merged:
            merged = False
            for i in range(len(nums)-1,0,-1):
                if (nums[i] >= 0 and nums[i-1] >= 0) or (nums[i] <= 0 and nums[i-1] <= 0):
                    nums[i-1] += nums.pop(i)
                    merged = True
            for i in range(len(nums)-2,0,-1):
                try:
                    if nums[i] <= 0 and (min(nums[i-1],nums[i+1]) + nums[i] >= 0):
                        print(nums[i-1:i+2])
                        nums[i-1] += nums.pop(i+1) + nums.pop(i)
                        merged = True
                except: pass


        for index, num in enumerate(nums):
            if num < 0: continue
            best = max(best,iterativeSolution(nums[index:]))
        return best

27900