大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題Day~
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Input: nums = [1]
Output: 1
Input: nums = [5,4,-1,7,8]
Output: 23
1 <= nums.length <= 3 * 104
-105 <= nums[i] <= 105
If you have figured out the O(n)
solution, try coding another solution using the divide and conquer approach, which is more subtle.
首先先簡單的翻譯一下題目
給定一個整數的陣列,從中找出總和最大的一個連續的子陣列(至少要有一個元素),並回傳總和最大的值。
這個題目最暴力的情況就是用兩個for loop去找最大總和,這樣的時間複雜度會是O(n^2)
。目標就先放在寫出O(n)
的演算法吧~
作法大致上是這樣
[-2,1,4,3]
,實際來跑一次流程看看。-2
,currentSum則是代表每次子陣列的總和。class Solution:
def maxSubArray(self, nums: List[int]) -> int:
maxSum = nums[0]
currentSum = 0
for num in nums:
if currentSum < 0:
currentSum = 0
currentSum += num
maxSum = max(maxSum, currentSum)
return maxSum
int maxSubArray(int* nums, int numsSize){
int maxSum = nums[0];
int currentSum = 0;
for (int i=0 ; i<numsSize ; i++){
if (currentSum < 0)
currentSum = 0;
currentSum += nums[i];
maxSum = (maxSum > currentSum? maxSum : currentSum);
}
return maxSum;
}
Python
C
大家明天見