diff --git a/best-time-to-buy-and-sell-stock/sol.rs b/best-time-to-buy-and-sell-stock/sol.rs new file mode 100644 index 0000000..9af2733 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/sol.rs @@ -0,0 +1,12 @@ +impl Solution { + pub fn max_profit(prices: Vec) -> i32 { + prices + .iter() + .fold((prices[0], 0), |(min, max_diff), &price| { + if price < min { + return (price, max_diff); + } + (min, max_diff.max(price - min)) + }).1 + } +} \ No newline at end of file diff --git a/divide-two-integers/sol.rs b/divide-two-integers/sol.rs new file mode 100644 index 0000000..e8cacae --- /dev/null +++ b/divide-two-integers/sol.rs @@ -0,0 +1,31 @@ +// Assume shift operators are allowed +impl Solution { + #[inline] + pub fn negative(n: i32) -> i32 { + if n.is_positive() { + return !(n - 1); + } + n + } + pub fn divide(dividend: i32, divisor: i32) -> i32 { + let positive = dividend ^ divisor >= 0; + let negative_divisor = Solution::negative(divisor); + let negative_answer = (0..negative_divisor.leading_ones()) // Preform all arithmetic in negative because of larger available range of numbers + .rev() // Reverse to get most extreme subdivisor first + .map(|n| negative_divisor << n) // Generate subdivisors + .fold((0, Solution::negative(dividend)), |(quotient, carry), subdivisor| { + if subdivisor >= carry { + return ((quotient << 1) - 1, carry - subdivisor); + } + return (quotient << 1, carry); + }).0; + if positive { + let answer = !negative_answer; + if answer != std::i32::MAX { + return answer + 1; + } + return answer; + } + negative_answer + } +} \ No newline at end of file diff --git a/intersection-of-two-arrays-ii/sol.rs b/intersection-of-two-arrays-ii/sol.rs new file mode 100644 index 0000000..a11e96f --- /dev/null +++ b/intersection-of-two-arrays-ii/sol.rs @@ -0,0 +1,26 @@ +use std::collections::HashMap; + +impl Solution { + pub fn intersect(nums1: Vec, nums2: Vec) -> Vec { + // Get longer & shorter side to optimise memory a little + let (longer, shorter) = if nums1.len() > nums2.len() { + (nums1.into_iter(), nums2.into_iter()) + } else { + (nums2.into_iter(), nums1.into_iter()) + }; + // Get counts of each element of shorter vector + let mut counts: HashMap = shorter + .fold(HashMap::new(), |mut counts, n| { + counts.insert(n, 1 + *counts.get(&n).unwrap_or(&0)); + counts + }); + // Filter longer vector using the counts of the elements of the shorter vector + longer + .filter(|n| { + let count = *counts.get(n).unwrap_or(&0); + counts.insert(*n, count - 1); + count.is_positive() + }) + .collect() + } +} \ No newline at end of file