본문 바로가기
LeetCode

LeetCode

by 콩순이냉장고 2022. 11. 11.

문제 URL : https://leetcode.com/problems/maximum-product-subarray/description/

 

Maximum Product 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

 

문제 접근법 : 연속적으로 곱해보고 0이면 다시 곱할수있도록 1로바꿔주면됩니다.

물론 앞에서 곱했을때와 뒤에서 곱했을때 , 둘중 최대값을 반환하면 되는 문제이기에

쉽게 이해할수있습니다.

 

소스코드 : 

 

 

 

#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
    int maxProduct(vector<int>& nums) {
        vector<int> v(nums.rbegin(), nums.rend());
        return max(getMax(nums),getMax(v));
    }
    int getMax(vector<int>& nums) {
        int res = -1e8;
        int p = 1;
        int before = -1e8;
        for (int i = 0; i < nums.size(); i++) {
            before = max(before, nums[i]);
            p *= nums[i];
            res = max({ res, before,p });
            if (p == 0)p = 1;
        }
        return res;
    }
};

궁금한점 혹은 모르는 점 어떤질문이든 댓글은 언제나 환영입니다.

'LeetCode' 카테고리의 다른 글

[LeetCode] 115. Distinct Subsequences  (0) 2023.08.26
LeetCode Valid Sudoku  (1) 2023.06.16
LeetCode 74 Search a 2D Matrix  (0) 2021.11.17
LeetCode 112 Path Sum  (0) 2021.11.14
LeetCode 257 Binary Tree Paths  (0) 2021.11.14