Below is the program I wrote to find sum of a subarray from given array, however somehow I am not getting how can I get rid of the sentinel value (-32767 in this case)? and how can I optimise it?
and how can I keep track of range of max subarray?
#define EVALUE -32767
using namespace std;
int findMaxSubArray(vector<int>,int low,int high);
int findMaxSubArray_Mid(vector<int>,int low,int high);
int main()
{
vector<int> v;
int j=0;
cout << "Enter array values(-32767 to end): ";
while(1)
{
cin >> j;
if (EVALUE==j)
break;
v.push_back(j);
}
if(v.size()!=0)
cout << "Max sum is: " << findMaxSubArray(v,0,v.size()-1) << "\n";
else
cout << "No array elements entered, exiting...\n";
system("pause");
return 0;
}
int findMaxSubArray(vector<int> v, int low, int high)
{
if(low==high) return v[low];
int max_mid_sum=findMaxSubArray_Mid(v,low,high);
int max_left_sum=findMaxSubArray(v,low,(low+high)/2);
int max_right_sum=findMaxSubArray(v,(low+high)/2+1,high);
if (max_mid_sum>max_left_sum) return (max_mid_sum>max_right_sum?max_mid_sum:max_right_sum);
else return(max_left_sum>max_right_sum?max_left_sum:max_right_sum);
}
int findMaxSubArray_Mid(vector<int> v,int low,int high)
{
int mid=high/2;
int max_left_sum=0;
int max_right_sum=0;
int sum=0;
for(int i=mid;i>=low;--i)
{
sum+=v[i];
if(sum>max_left_sum)
{
max_left_sum=sum;
}
}
sum=0;
for(int i=mid+1;i<=high;++i)
{
sum+=v[i];
if(sum>max_right_sum)
{
max_right_sum=sum;
}
}
return (max_right_sum+max_left_sum);
}
When reading from a textfile, the last character that cin will get is the “EOF” character, or end of file character. You can send this character to your program in the command line with control+d. You’re going to want to check for this rather than -32767.
This is a basic program that should identify a simple fix for your problem:
If you want to get really smart you can use the below and it will directly insert the contents of the memory at cin (from the beginning until EOF) into your vector. As far as running time goes, this will probably be faster than your solution and the above solution.