728x90
반응형
✨ 문제
Final Prices With a Special Discount in a Shop
You are given an integer array prices where prices[i] is the price of the ith item in a shop.
There is a special discount for items in the shop. If you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i]. Otherwise, you will not receive any discount at all .
Return an integer array answer where answer[i] is the final price you will pay for the ith item of the shop, considering the special discount.
https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/description/
✨ 최종코드
class Solution {
public int[] finalPrices(int[] prices) {
int n = prices.length;
int[] answer = new int[n];
for (int i = 0; i < n; i++) {
answer[i] = prices[i]; // 초기값 설정
for (int j = i + 1; j < n; j++) {
if (prices[j] <= prices[i]) {
answer[i] = prices[i] - prices[j];
break; // 할인 적용 후 루프 탈출
}
}
}
return answer;
}
}
728x90
반응형