Skip to content

Commit

Permalink
[problem] minimize-deviation-in-array
Browse files Browse the repository at this point in the history
  • Loading branch information
goodstudyqaq committed Nov 27, 2023
1 parent 337e8dc commit 9deb9fc
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 0 deletions.
8 changes: 8 additions & 0 deletions problems-cpp/minimize-deviation-in-array/data
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[1,2,3,4]
1
[4,1,5,20,3]
3
[2,10,8]
3
[3,5]
1
47 changes: 47 additions & 0 deletions problems-cpp/minimize-deviation-in-array/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#include "./solution.h"

int main() {
Solution sol = Solution();
// Read data from file
ifstream infile;
infile.open("./data", ios::in);
string strLine;

int input_number = 1;
int output_number = 1;
int one_test_number = input_number + output_number;
vector<string> data;

while (getline(infile, strLine)) {
if (strLine.size()) {
data.push_back(strLine);
}
}
if (data.size() % (one_test_number)) {
cerr << "The format of test data is incorrect" << endl;
return 0;
}
int test_number = data.size() / one_test_number;

int all_test = test_number;
int fail_test = 0;

for (int i = 0; i < test_number; i++) {
cerr << "Case " << to_string(i + 1) + " testing..." << endl;

vector<int> nums;
convert_params(data[i * one_test_number + 0], nums);
int real_res;
convert_params(data[i * one_test_number + 1], real_res);

int my_res = sol.minimumDeviation(nums);

bool check_result = compare_result(to_string(i + 1), my_res, real_res);
if (!check_result) {
fail_test++;
}
}
cerr << "The number of test cases: " << test_number << endl;
cerr << "The number of test cases failed: " << fail_test << endl;
return 0;
}
41 changes: 41 additions & 0 deletions problems-cpp/minimize-deviation-in-array/solution.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
Code generated by https://github.com/goodstudyqaq/leetcode-local-tester
*/
#if __has_include("../utils/cpp/help.hpp")
#include "../utils/cpp/help.hpp"
#elif __has_include("../../utils/cpp/help.hpp")
#include "../../utils/cpp/help.hpp"
#else
#define debug(...) 42
#endif

class Solution {
public:
int minimumDeviation(vector<int>& nums) {
int n = nums.size();
int p_mx = 1;
for (int i = 0; i < n; i++) {
if (nums[i] % 2)
nums[i] *= 2;
p_mx = max(p_mx, nums[i] >> __builtin_ctz(nums[i]));
}
int mi = p_mx;
vector<int> V;
for (int i = 0; i < n; i++) {
mi = min(mi, nums[i]);
while (nums[i] / 2 >= p_mx) {
nums[i] /= 2;
}
if (nums[i] >= p_mx)
V.push_back(nums[i]);
}
sort(V.begin(), V.end());
int ans = V.back() - mi;
debug(V, mi, p_mx);
for (int i = V.size() - 1; i > 0; i--) {
mi = min(mi, V[i] / 2);
ans = min(ans, V[i - 1] - mi);
}
return ans;
}
};

0 comments on commit 9deb9fc

Please sign in to comment.