Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
从阵列中,求出最大连续元素的总和。
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Input: nums = [1]
Output: 1
Input: nums = [0]
Output: 0
Input: nums = [-1]
Output: -1
遍历阵列,若连续元素相加的值大於最大值max
,则取代max
。
var maxSubArray = function(nums) {
let sum = 0;
let max = nums[0];
for (let i = 0; i < nums.length; i++) {
for (let j = i; j < nums.length; j++) {
sum += nums[j];
if (max < sum) max = sum;
}
sum = 0;
}
return max;
};
<<: Day 28 axios-login(vue cli)
策略(Strategy) 自定义策略 class SmaCrossCons(ConsStrategy...
什麽是 ORM? ORM 是 Object Relational Mapping 的缩写,中⽂翻译成...
系列文接近尾声,专案最後要来做一个过渡动画效果 我们要做的效果是向左/右滑入滑出,效果可以参考 V...
介绍完决策树和随机森林後,今天来介绍的是 K-近邻演算法(k-nearest neighbor cl...
昨天讲了怎麽将阵列的东西叫出来,那今天讲要怎麽知道阵列里面有多少笔资料 其实用 length 就好了...