iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 16
0
自我挑戰組

用LeetCode來訓練大腦的邏輯思維系列 第 27

LeetCode 53. Maximum Subarray

  • 分享至 

  • xImage
  •  

題目

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;
};

上一篇
LeetCode 387. First Unique Character in a String
下一篇
LeetCode 1. Two Sum
系列文
用LeetCode來訓練大腦的邏輯思維30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言