LeetCode 53. Maximum Subarray

题目

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.

题意

从阵列中,求出最大连续元素的总和。

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6

Example 2:

Input: nums = [1]
Output: 1

Example 3:

Input: nums = [0]
Output: 0

Example 4:

Input: nums = [-1]
Output: -1

解题想法

遍历阵列,若连续元素相加的值大於最大值max,则取代max

Solution

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)

>>:  Day 30 - 後记

[Day 15] backtesting 使用说明

策略(Strategy) 自定义策略 class SmaCrossCons(ConsStrategy...

Ruby on Rails Model 基本操作之 CRUD CRUD 之 C(Create)

什麽是 ORM? ORM 是 Object Relational Mapping 的缩写,中⽂翻译成...

Day 28. F2E-过渡动画

系列文接近尾声,专案最後要来做一个过渡动画效果 我们要做的效果是向左/右滑入滑出,效果可以参考 V...

Day 20 K-近邻演算法(KNN)

介绍完决策树和随机森林後,今天来介绍的是 K-近邻演算法(k-nearest neighbor cl...

JavaScript入门 Day17_阵列3

昨天讲了怎麽将阵列的东西叫出来,那今天讲要怎麽知道阵列里面有多少笔资料 其实用 length 就好了...