subset_min_max_count.cpp
This commit is contained in:
74
puzzles/interviews/training/subset_min_max_count.cpp
Normal file
74
puzzles/interviews/training/subset_min_max_count.cpp
Normal file
@@ -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 <iostream>
|
||||||
|
#include <exception>
|
||||||
|
#include <chrono>
|
||||||
|
#include <vector>
|
||||||
|
#include <algorithm>
|
||||||
|
|
||||||
|
/*
|
||||||
|
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<int> 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<double> 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;
|
||||||
|
}}
|
||||||
Reference in New Issue
Block a user