[Programmers] 할인 행사

김토리·2024년 9월 25일

알고리즘

목록 보기
18/27


이 문제는 내가 생각하는 풀이가 비효율적인 것 같아 인터넷에서 서칭하여 풀이를 참고 했다.

풀이 방법은

  1. 원하는 할인 품목(want)과 갯수(number)를 맵핑한 map을 만든다.
    -> map <string,int> wantItems;
    ex) wantItems[banana] = 3;
  2. 마트에서 할인하는 제품들(discount)를 순차적으로 10개씩 비교하며 회원가입이 가능하다면 answer에 1을 더해준다.
    -> map <string,int > m;를 1차 반복문에 선언하여 wantItems과 비교할 수 있도록 한다.
    #include <string>
    #include <vector>
    #include <map>
    using namespace std;
    map <string,int> wantItems;
    bool check(map<string,int > m){
      for(auto u: wantItems){
          if(m.find(u.first) == m.end() ){
          //할인 품목에 원하는 품목이 없을 경우
              return false;
          }else if(m[u.first] != u.second ){
          //수량이 일치하지 않을 경우
              return false;
          }
      }
      return true;
    }
    int solution(vector<string> want, vector<int> number, vector<string> discount) {
      int answer = 0 ;
      
      //원하는 할인 품목과 갯수 맵핑
      for(int i  = 0 ; i < want.size() ; i++ ){
          wantItems[want[i]] = number[i];
      }
      
      for(int i  = 0 ; i <= discount.size()-10 ; i++ ){
          map <string,int > m;
          
          for(int j = i ; j < i +10 ; j++ ){
              m[discount[j]]++;
          }
          answer+=check(m);
       
          m.clear();
      }
      return answer;
    }
profile
웹 개발하며 데이터 분석, AI 공부하는 jinveloper

0개의 댓글