본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1475. Final Prices With a Special Discount in a Shop

반응형

https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/description/

간단 구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

1. 구조체 Info를 선언 후 member변수에 index와 price를 선언합니다.2. 정답 vector ans를 선언해줍니다.

📔 풀이과정

prices에 대해 2차원 for loop를 수행합니다.

1. 지역변수 info를 선언해 현재 price의 index와 price정보를 저장합니다.

2. 다시 for loop를 현재 index다음부터 수행하면서 현재 price보다 작다면 index와 price를 갱신합니다.

3. 갱신된 정보가 없다면 현재 price값을, 아니라면 할인된 가격을 ans에 저장합니다.

📔 정답 출력 | 반환

ans를 반환합니다.


📕 Code

📔 C++

struct Info {
    int index;
    int price;
};

class Solution {
public:
    vector<int> finalPrices(vector<int>& prices) {
        vector <int> ans;
        for(int i = 0; i < prices.size(); i++) {
            Info info = {i, prices[i]};
            for(int j = i+1; j < prices.size(); j++) {
                if(info.price >= prices[j]) {
                    info.index = j;
                    info.price = prices[j];
                    break;
                }
            }
            int disCountedPrice = info.index == i ? prices[i] : prices[i] - info.price;
            ans.push_back(disCountedPrice);
        }
        return ans;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.