Maximum Subarray

2025. 1. 5. 15:53·PS/LeetCode
반응형

문제

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

입력

1 <= nums.length <= 105
-10^4 <= nums[i] <= 10^4

결과

ans: Int = 가장 큰 부분수열의 합

해석

누적합이 현재 값보다 작으면, 이전 누적합을 버리고 그렇지 않으면 계속 누적한다.

이 때 누적할 때마다 이전의 최대값과 계속 비교해서 저장한다.

코드

class Solution {
    func maxSubArray(_ nums: [Int]) -> Int {
        let len = nums.count 
        var currentMax = nums[0] // 누적합
        var ans = nums[0] // 최종 결과 
        
        for i in 1..<len {
            currentMax = max(nums[i], currentMax+nums[i]) // 누적합이 더 작으면 현재껄로 새로 시작
            ans = max(currentMax, ans) // 최대값 갱신
        }
        return ans
    }
}

 

반응형

'PS > LeetCode' 카테고리의 다른 글

Find Minimum in Rotated Sorted Array  (0) 2025.01.08
Maximum Product Subarray  (0) 2025.01.08
Product of Array Except Self  (0) 2025.01.05
Best Time to Buy and Sell Stock  (0) 2025.01.05
Two Sum  (0) 2025.01.05
'PS/LeetCode' 카테고리의 다른 글
  • Find Minimum in Rotated Sorted Array
  • Maximum Product Subarray
  • Product of Array Except Self
  • Best Time to Buy and Sell Stock
Hamp
Hamp
남들에게 보여주기 부끄러운 잡다한 글을 적어 나가는 자칭 기술 블로그입니다.
  • Hamp
    Hamp의 분리수거함
    Hamp
  • 전체
    오늘
    어제
    • 분류 전체보기 (304)
      • CS (30)
        • 객체지향 (2)
        • Network (7)
        • OS (6)
        • 자료구조 (1)
        • LiveStreaming (3)
        • 이미지 (1)
        • 잡다한 질문 정리 (0)
        • Hardware (2)
        • 이론 (6)
        • 컴퓨터 그래픽스 (0)
      • Firebase (3)
      • Programing Langauge (37)
        • swift (32)
        • python (4)
        • Kotlin (1)
      • iOS (132)
        • UIKit (37)
        • Combine (1)
        • SwiftUI (32)
        • Framework (7)
        • Swift Concurrency (22)
        • Tuist (6)
        • Setting (11)
        • Modularization (1)
        • Instruments (6)
      • PS (59)
        • 프로그래머스 (24)
        • 백준 (13)
        • LeetCode (19)
        • 알고리즘 (3)
      • Git (18)
        • 명령어 (4)
        • 이론 (2)
        • hooks (1)
        • config (2)
        • action (7)
      • Shell Script (2)
      • Linux (6)
        • 명령어 (5)
      • Spring (13)
        • 어노테이션 (1)
        • 튜토리얼 (11)
      • CI-CD (4)
      • Android (0)
        • Jetpack Compose (0)
  • 블로그 메뉴

    • 홈
    • 태그
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    boostcamp
    dispatch
    SwiftUI
    CS
    dfs
    lifecycle
    AVFoundation
    protocol
    property
    투포인터
    Spring
    UIKit
    concurrency
    IOS
    Swift
    백준
    dp
    Tuist
    프로그래머스
    GIT
  • 최근 댓글

  • 최근 글

  • 반응형
  • hELLO· Designed By정상우.v4.10.0
Hamp
Maximum Subarray
상단으로

티스토리툴바