본문 바로가기
IT/알고리즘

29★] Leetcode 1013. Partition Array Into Three Parts With Equal Sum

by 깻잎쌈 2020. 7. 7.
반응형

https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/

 

Partition Array Into Three Parts With Equal Sum - 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

int 벡터를 공백이 아니고 합이 같은 세 개의 부분 배열로 나눌 수 있는지 묻는 문제.

class Solution {
public:
    bool canThreePartsEqualSum(vector<int>& A) {
        int sum = 0;
        for(auto i:A)
            sum+=i;
        
        if(sum %3 != 0)
            return false;
        
        int groupNum = 0;
        int cnt = 0;
        for(int i = 0; i<A.size(); i++){
            cnt+=A[i];
            if(cnt== (sum/3)){
                cnt =0;
                groupNum++;
            }
        }
            
        if(groupNum >= 3) //★
            return true;
        else 
            return false;
    }
};

{10,-10, 10,-10, 10,-10., 10,-10}의 경우

0이 4번 나오게 4개로도 나눌 수 있지만 3개(0, 0, (0+0))로도 나눌 수 있기 때문에

나눌 수 있는 부분이 3개이상이면 true

반응형

댓글