Member-only story
Leetcode 1475: Final Prices With a Special Discount in a Shop
2 min readJun 14, 2020
In this Leetcode problem, we want to find the real prices of items given a special discount rule.
Solution
A couple of ideas for the solution:
- Create a new array
res
to hold the result of the method (we could very well use the input array too, and there is no problem doing that) - For each item
i
look for the indexj
corresponding to the discount, if it exists, by checking all the indices afteri
, and picking the first one for which the ruleprices[j] ≤ prices[i]
applies. - If we found
j
apply the discount in the arrayres
- When all is done, return the res array.
class Solution {
public int[] finalPrices(int[] prices) {
int n = prices.length;
int[] res = new int[n];
for (int i = 0; i < n; i++) {
int p = prices[i];
res[i] = p;
for (int j = i + 1; j < n; j++) {
if (prices[j] <= prices[i]) {
res[i] -= prices[j];
break;
}
}
}
return res;
}
}
This algorithm is O(n²) in time, beats 100% of the Java solutions.
Happy coding!
What’s next:
- Checkout the solution for another problem: Rearrange words in a sentence
- Contact me: poitevinpm@gmail.com
- Looking to interview for a software engineer position? Contact me :)