Maximum subarray in challenges

i saw all your approaches to maximum subarray with n2 and n3 complexity. in the challenge i used a different logic, but it doesnt pass the testcases, only the example, the logic is this=> take an array, sort the array, start counting sum from last element and keep adding as long as sum increases. and print the sum which is equal to max subarray sum. this is the link to my code:


please explain the flaw in my logic and/or how to correct the code to pass all testcases.

Hey @ilovetocode since the questions asks for maximum subarray sum you cannot sort the array because subarray is an array composed from contiguous blocks of original array and sorting an array results in different array. for example if we take array {1, -1, 1, -1} the maximum subarray sum is 1 but if we sort the array it becomes {-1, -1, 1, 1} and now maximum subarray sum is 2. Also the logic being used is incorrect, what you essentially need to do is to keep track of maximum sum contiguous segment among all the positive segments.
Let me know if you need more help regarding the same.