Given an integer array nums, please find a continuous subarray with the largest sum (the subarray contains at least one element), and return its largest sum.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The sum of consecutive subarrays [4,-1,2,1] is the largest, which is 6.
Example 2:
input: nums = [1]
output: 1
Example 3:
Input: nums = [5,4,-1,7,8]
Output: 23
hint:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
Advanced: If you have implemented a solution with complexity O(n), try to solve it with a more sophisticated divide and conquer method.
Can't pass the use case
/**
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function(nums) {
// 1.去除数组中重复的元素
let setNums = new Set(nums)
let arr = [...setNums]
// 2.获取连续和最大的数值
arr.sort()
let max = 0
let thisMax = 0
for (var i = 0; i < arr.length; i++) {
thisMax += arr[i];
if (thisMax < arr[i]) {
thisMax = arr[i]
}
if (thisMax > max) {
max = thisMax
}
}
// console.log(arr, max)
return max
};