aboutsummaryrefslogtreecommitdiff
path: root/other/min_deviation_arr.cpp
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
committerJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
commit7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch)
treeeb7a24ee2067f92245c57bb118e85a1baf15df50 /other/min_deviation_arr.cpp
parent5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff)
downloadleetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz
leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip
chore: move cpp and rust code to directory
Diffstat (limited to 'other/min_deviation_arr.cpp')
-rw-r--r--other/min_deviation_arr.cpp36
1 files changed, 36 insertions, 0 deletions
diff --git a/other/min_deviation_arr.cpp b/other/min_deviation_arr.cpp
new file mode 100644
index 0000000..47099a6
--- /dev/null
+++ b/other/min_deviation_arr.cpp
@@ -0,0 +1,36 @@
+// 1675. Minimize Deviation in Array
+#include "leetcode.h"
+
+/*
+ * the deviation of the array is the maximum difference between any two elements
+ * in the array. return minimum deviation the array can have after performing
+ * 'nums' ops.
+ */
+
+class Solution {
+public:
+ int minimumDeviation(vector<int> nums) {
+ int ans = INT_MAX, min_nums = INT_MAX;
+ for (int i = 0; i < nums.size(); ++i) {
+ nums[i] = nums[i] % 2 ? nums[i] * 2 : nums[i];
+ min_nums = min(min_nums, nums[i]);
+ }
+ make_heap(begin(nums), end(nums));
+ while (nums[0] % 2 == 0) {
+ ans = min(ans, nums[0] - min_nums);
+ min_nums = min(min_nums, nums[0] / 2);
+ pop_heap(begin(nums), end(nums));
+ nums.back() /= 2;
+ push_heap(begin(nums), end(nums));
+ }
+ return min(ans, nums[0] - min_nums);
+ }
+};
+
+int main() {
+ Solution obj;
+ vector<int> n1 = {1, 2, 3, 4}, n2 = {4, 1, 5, 20, 3}, n3 = {2, 10, 8};
+ cout << obj.minimumDeviation(n1) << endl; // expect: 1
+ cout << obj.minimumDeviation(n2) << endl; // expect: 3
+ cout << obj.minimumDeviation(n3) << endl; // expect: 3
+}