longest_chain_equal_K.cpp

This commit is contained in:
2018-10-06 13:31:42 +01:00
parent cc53adcb1f
commit 6398bb5e4b

View File

@@ -0,0 +1,89 @@
/*
VIM: let b:lcppflags="-std=c++14 -O2 -pthread -I."
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
*/
#include <iostream>
#include <exception>
#include <chrono>
#include <algorithm>
#include <vector>
#include <unordered_map>
/*
snap-inc-interview-questions
You are given an array of integers and a number K. You have to find the any
continue sub-array whose elements sum is K. Please note that, the array may
have positive, negative, and zeros as its element.
The desired complexity is O(N).
Example:
Input: [7 0 9 -10 0 789], K = 0
Output: Array from index 1 to Index 1.
Input: [1 2 3 5 -10] K = 0
Output: Array from Index 1 to Index 4.
If K = -2, Output would have been SubArray from Index 2 to Index 4.
*/
void solution( std::vector<int> v, int K )
{
int f = -1;
int l = -2;
std::unordered_map<int, int> m;
int s = 0;
for ( int i = 0; i < v.size(); ++i ) {
s+= v[i];
auto p = m.emplace( s, i);
if ( !p.second ){
p.first->second = i;
}
}
s = 0;
for ( int i = 0; i < v.size(); ++i ) {
auto r = m.find(s+K);
if ( r != m.end() && l-f < r->second - i){
l = r->second;
f = i;
}
s+= v[i];
}
std::cout << " {";
for ( auto i : v ){
std::cout << i << ", ";
}
std::cout << "}, " << K << " -> (" << f << ", " << l << ")" << std::endl;
}
int main ( void )
{try{
solution({7, 0, 9, -10, 0, 789}, 0);
solution({1, 2, 3, 5, -10}, 0);
solution({1, 2, 3, 5, -10}, -2);
solution({1, 2, 3, 5, -10}, -10);
solution({1, 2, 3, 5, -10}, 1);
solution({7, 2, 9, -10, 0, 789}, 7);
solution({7, 2, 9, -10, 0, 789}, 10000);
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;
}}