aboutsummaryrefslogtreecommitdiff
path: root/other/min_max_array.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_max_array.cpp
parent5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff)
downloadleetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz
leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip
chore: move cpp and rust code to directory
Diffstat (limited to 'other/min_max_array.cpp')
-rw-r--r--other/min_max_array.cpp43
1 files changed, 43 insertions, 0 deletions
diff --git a/other/min_max_array.cpp b/other/min_max_array.cpp
new file mode 100644
index 0000000..6da3f2b
--- /dev/null
+++ b/other/min_max_array.cpp
@@ -0,0 +1,43 @@
+// 2439. Minimize Maximum of Array
+#include "leetcode.h"
+
+/*
+ * given a 0-indexed array 'nums' comprising of n unsigned integers. ine one
+ * operation you must choose an integer 'i' such that '1 <= i < n' and 'nums[i]
+ * > 0'. decrease 'nums[i]' by 1 or increase 'nums[i]' by 1. return minimum
+ * possible value of the max integer 'nums' after performing any number of
+ * operations.
+ */
+
+class Solution {
+ bool valid(vector<int> &nums, int mid) {
+ long sum = 0;
+ for (int i = 0; i < nums.size(); i++) {
+ sum += nums[i];
+ if (sum > (long)mid * (i + 1))
+ return false;
+ }
+ return true;
+ }
+
+public:
+ int minimizeArrayValue(vector<int> &nums) {
+ int left = 0, right = *max_element(nums.begin(), nums.end()), ans = 0;
+ while (left <= right) {
+ int mid = (left + right) >> 1;
+ if (valid(nums, mid)) {
+ ans = mid;
+ right = mid - 1;
+ } else
+ left = mid + 1;
+ }
+ return ans;
+ }
+};
+
+int main() {
+ Solution obj;
+ vector<int> n1 = {3, 7, 1, 6}, n2 = {10, 1};
+ printf("%d\n", obj.minimizeArrayValue(n1)); // expect: 5
+ printf("%d\n", obj.minimizeArrayValue(n2)); // expect: 10
+}