Given MSalters comments, I am afraid that another solution would be better. If you want to use less memory, the selected answer may be good enough, but you can use the following code to find possible solutions:
static const int arr[] = {5,-10,10,-10,10,1,1,1,1,1}; std::vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) ); // compute cumulative sum std::vector<int> cumulative_sum( vec.size() ); cumulative_sum[0] = vec[0]; for ( size_t i = 1; i < vec.size(); i++ ) { cumulative_sum[i] = cumulative_sum[i-1] + vec[i]; } const int complete_sum = cumulative_sum.back(); // find multiple solutions, if there are any const int complete_sum_half = complete_sum / 2; // suggesting this is valid... std::vector<int>::iterator it = cumulative_sum.begin(); std::vector<int> mid_indices; do { it = std::find( it, cumulative_sum.end(), complete_sum_half ); if ( it != cumulative_sum.end() ) { mid_indices.push_back( it - cumulative_sum.begin() ); ++it; } } while( it != cumulative_sum.end() ); for ( size_t i = 0; i < mid_indices.size(); i++ ) { std::cout << mid_indices[i] << std::endl; } std::cout << "Split behind these indices to obtain two equal halfs." << std::endl;
Thus, you get all possible solutions. If there is no solution to split the vector into two equal halves, then mid_indices will remain empty. Again, you should sum each value only once.
My suggestion is this:
static const int arr[] = {1,2,3,5,4,-1,1,1,2,-1}; std::vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) ); int idx1(0), idx2(vec.size()-1); int sum1(0), sum2(0); int idxMid = -1; do { // fast access without using the index each time. const int& val1 = vec[idx1]; const int& val2 = vec[idx2]; // Precompute the next (possible) sum values. const int nSum1 = sum1 + val1; const int nSum2 = sum2 + val2; // move the index considering the balanace between the // left and right sum. if ( sum1 - nSum2 < sum2 - nSum1 ) { sum1 = nSum1; idx1++; } else { sum2 = nSum2; idx2--; } if ( idx1 >= idx2 ){ idxMid = idx2; } } while( idxMid < 0 && idx2 >= 0 && idx1 < vec.size() ); std::cout << idxMid << std::endl;
It adds each value only once no matter how many values. Such complexity is only O (n), not O (n ^ 2).
The code just runs left and right at the same time and moves the indexes further if it is smaller than the other. C>