[leetcode #53] Maximum Subarray

Seongyeol Shin·2021년 11월 25일
0

leetcode

목록 보기
87/196
post-thumbnail

Problem

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.

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Example 2:

Input: nums = [1]
Output: 1

Example 3:

Input: nums = [5,4,-1,7,8]
Output: 23

Constraints:

・ 1 <= nums.length <= 10⁵
・ -10⁴ <= nums[i] <= 10⁴

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.

Idea

합이 최대가 되는 subarray를 찾고 그 합을 구하는 문제다.

O(n)으로 풀지 않으면 Times Limit Exceeded가 뜬다. Brute force로 풀면 array를 탐색하면서 가능한 모든 subarray를 비교하게 될 것이다.

코드는 짧지만 subarray의 합이 최대가 되는 경우를 잘 생각해야 한다. currentSum이라는 값을 두고, maxSum이라는 값을 따로 둔다. currentSum은 이전에 구한 합과 현재의 값을 비교하여 더 큰 값을 저장하는 변수다. maxSum은 첫 번째 값으로 초기화한 뒤 currentSum과 비교해 더 큰 값을 항상 저장한다.

currentSum은 현재 index의 값을 포함하는 값 중 최대가 되는 합이고, maxSum은 전체 array에서 최대가 되는 합이라고 생각하면 된다. 매번 index를 바꿀 때마다 이전에 구한 최대값과 현재 index를 포함하는 subarray의 최대값을 비교하는 것이다.

Solution

class Solution {
    public int maxSubArray(int[] nums) {

        int currentSum = nums[0];
        int maxSum = nums[0];

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

        return maxSum;

    }
}

Reference

https://leetcode.com/problems/maximum-subarray/

profile
서버개발자 토모입니다

0개의 댓글