LeetCode Entry
1357. Apply Discount Every n Orders
Disign 'buy([ids],[amounts])->money' with given [ids],[prices],nth, discount
1357. Apply Discount Every n Orders medium substack youtube
https://dmitrysamoylenko.com/leetcode/

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1558
Problem TLDR
Disign ‘buy([ids],[amounts])->money’ with given [ids],[prices],nth, discount
Intuition
Brute-force is accepted. Some optimisation: precompute hash map ids to price.
Approach
- Rust itertools izip! is shorter than zip
- fastest solution is a lookup array of 201 elements
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(n)\)
Code
class Cashier(val n: Int, d: Int, pd: IntArray, pr: IntArray) {
val p = pd.zip(pr).toMap()
var i = 1; val d = 1-d/1e2
fun getBill(pd: IntArray, a: IntArray) =
pd.zip(a){x,y->p[x]!!*y}.sum()*if(i++%n<1) d else 1.0
}
struct Cashier(i32, f64, HashMap<i32, i32>, i32);
impl Cashier {
fn new(n: i32, d: i32, b: Vec<i32>, c: Vec<i32>) -> Self {
Self(n, 1. - d as f64 / 1e2, izip!(b, c).collect(), 0)
}
fn get_bill(&mut self, b: Vec<i32>, a: Vec<i32>) -> f64 {
self.3 += 1;
izip!(&b, a).fold(0, |s, (x, y)| s + self.2[x] * y) as f64
* if self.3 % self.0 < 1 { self.1 } else { 1. }
}
}
Comments