ETC/Algorithm

[LeetCode] 53. Maximum Subarray

Pazery는ENFJ 2021. 12. 30. 17:39
반응형

 

 

Maximum Subarray - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

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^5
  • -10^4 <= nums[i] <= 10^4

주어진 배열에서 연속된 배열의 값의 합 중 최대의 값을 갖는 값을 리턴하는 문제였다

간단할 줄 알았지만 간단하지 않은 문제였다.

혼자 이런 저런 고민하다 스터디원들의 도움을 받아 해결 한 문제!

class Solution {
    public int maxSubArray(int[] nums) {
        int numsLength = nums.length;
        int max = nums[0];
        int sumArrayVal = nums[0];
        for(int idx = 1; idx < numsLength; idx++){
            if(nums[idx] < sumArrayVal + nums[idx]){
               sumArrayVal = sumArrayVal + nums[idx];
            } else{
               sumArrayVal = nums[idx]; 
            }
            if(max < sumArrayVal){
                max = sumArrayVal;
            }
        }
        return max;
    }
}

반응형