LeetCode #53 Maximum Subarray 最大的子陣列

LeetCode題目翻譯

英文原文如下

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

subarray is a contiguous part of an array.

中文翻譯

給予一個整數陣列 nums,尋找一個值加總最大的相鄰子陣列 (至少包含一個數字) 並回傳其加總

一個子陣列指的是一個陣列中相連的部分

範例及題目限制


解題思路

這題最重要的就是相鄰這兩個字

所以我們的解決方法肯定是用迴圈來處理,而如何僅在一次迴圈中完成就很重要了 (壓低時間複雜度)

C# 解決方案

方案1

public class Solution {
    public int MaxSubArray(int[] nums) {
        int max = nums[0];
        int tmp =0;
        for(int i = 0;i<nums.Length;i++)
        {
            tmp+=nums[i];
            if(tmp>max)
            {
                max = tmp;
            }
            if(tmp<0)
            {
                tmp = 0;
            }
        }
        return max;
    }
}

時間複雜度 :  O(n)

在這個解決方法,我們用了陣列中的第一個數字來當一個暫定的變數 ➡ max,用來進行後續的比較

然後正常跑著遞迴,若tmp值大於當前max則取代

若tmp小於 0 則設為 0,意思其實就是加總值根本對最大值沒有幫助,故從下一個索引繼續判斷

Java解決方案

方案1

class Solution {
    public int maxSubArray(int[] nums) {
        int max = nums[0];
        int tmp =0;
        for(int i = 0;i<nums.length;i++)
        {
            tmp+=nums[i];
            if(tmp>max)
            {
                max = tmp;
            }
            if(tmp<0)
            {
                tmp = 0;
            }
        }
        return max;
    }
}

Python3 解決方案

方案1

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        max = nums[0]
        tmp =0
        for i in range(0,len(nums)):
            tmp+=nums[i]
            
            if(tmp>max):
                max = tmp
            
            if(tmp<0):
            
                tmp = 0
            
        return max

JavaScript 解決方案

方案1

/**
 * @param {number[]} nums
 * @return {number}
 */
var maxSubArray = function(nums) {
    var max = nums[0];
    var tmp =0;
    for(var i = 0;i<nums.length;i++)
    {
        tmp+=nums[i];
        if(tmp>max)
        {
            max = tmp;
        }
        if(tmp<0)
        {
            tmp = 0;
        }
    }
    return max;
};

結論

🧡如果這篇文章有幫上你的一點點忙,那是我的榮幸

🧡收藏文章或幫我分享,我都會很感謝的

✅如有任何疑問,歡迎透過留言或messenger讓我知道 !

題目連結 : Maximum Subarray – LeetCode

一些隨機文章

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *