[LeetCode] Maximum Subarray

 

1. ๋ฌธ์ œ : Link

ํ•˜์œ„ array ์ค‘ ํ•ฉ์˜ ์ตœ๋Œ€๊ฐ’ ์ฐพ๋Š” ๋ฌธ์ œ

 

2. ํ’€์ด

array๋ฌธ์ œ ์œ ํ˜•์— ์žˆ๊ธธ๋ž˜ dp ์ƒ๊ฐ๋„ ๋ชปํ–ˆ๋Š”๋ฐ dp ๋ฌธ์ œ์—ฌ๋”ฐ...

 

3. ์ฝ”๋“œ

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        dp = [num for num in nums]
        for i in range(1, len(nums)):
            dp[i] = max(dp[i-1]+nums[i], nums[i])

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

    for(int i=1; i<nums.length; i++){
        dp[i] = Math.max(dp[i-1] + nums[i], nums[i]);
    }

    int max = Integer.MIN_VALUE;
    for(int i=0; i<nums.length; i++){
        if(dp[i] > max) max = dp[i];
    }

    return max;
    }
}
  • ๋„ค์ด๋ฒ„ ๋ธ”๋Ÿฌ๊ทธ ๊ณต์œ ํ•˜๊ธฐ
  • ๋„ค์ด๋ฒ„ ๋ฐด๋“œ์— ๊ณต์œ ํ•˜๊ธฐ
  • ํŽ˜์ด์Šค๋ถ ๊ณต์œ ํ•˜๊ธฐ
  • ์นด์นด์˜ค์Šคํ† ๋ฆฌ ๊ณต์œ ํ•˜๊ธฐ