From 1fd221977717468d59f0991316bd1d0895ace310 Mon Sep 17 00:00:00 2001 From: Vahagn Khachatryan Date: Sun, 10 Mar 2019 13:22:31 +0000 Subject: [PATCH] subset_min_max_count.cpp --- .../training/subset_min_max_count.cpp | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 puzzles/interviews/training/subset_min_max_count.cpp diff --git a/puzzles/interviews/training/subset_min_max_count.cpp b/puzzles/interviews/training/subset_min_max_count.cpp new file mode 100644 index 0000000..6451e66 --- /dev/null +++ b/puzzles/interviews/training/subset_min_max_count.cpp @@ -0,0 +1,74 @@ +/* +VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I." +VIM: let b:wcppflags="/O2 /EHsc /DWIN32" +*/ +#include "stdafx.h" +#include +#include +#include +#include +#include + +/* + google-interview-questions + For a given vector of integers and integer K, find the number of non-empty subsets S such that min(S) + max(S) <= K + For example, for K = 8 and vector [2, 4, 5, 7], the solution is 5 ([2], [4], [2, 4], [2, 4, 5], [2, 5]) + The time complexity should be O(n2). Approach and code was asked +*/ + +int countSubsets(std::vector numbers, int k) +{ + int total_sum = 0; + for (int i = 0; i < numbers.size(); ++i) { + + if (2 * numbers[i] > k) { + continue; + } + + int sum = 1; + int max = numbers[i]; + int min = numbers[i]; + for (int j = i+1; j < numbers.size(); ++j) { + int tmp_max = std::max(max, numbers[j]); + int tmp_min = std::min(min, numbers[j]); + + if (tmp_max + tmp_min <= k) { + sum *= 2; + min = tmp_min; + max = tmp_max; + } + } + total_sum += sum; + } + + return total_sum; +} + +int main() +{try{ + auto begin = std::chrono::high_resolution_clock::now(); + + + //...... + std::cout << countSubsets({ 2, 4, 5, 7 }, 8) << std::endl; + + + + + auto end = std::chrono::high_resolution_clock::now(); + std::chrono::duration seconds = end - begin; + std::cout << "Time: " << seconds.count() << std::endl; + return 0; +} +catch ( const std::exception& e ) +{ + std::cerr << std::endl + << "std::exception(\"" << e.what() << "\")." << std::endl; + return 2; +} +catch ( ... ) +{ + std::cerr << std::endl + << "unknown exception." << std::endl; + return 1; +}}