Answer:
Solution 1:
Recursively computing the array sum is one of the options, but no optimal.
The trick is to build the array iteratively from the previous results,
for ex: A[0..4]= a[0..3] + A[4]
Complexity : O(m*n/2)
#include
#include
#include
#include
using namespace std;
int main(int argc, char *argv[])
{
if (argc <= 1)
return -1;
vectora(argc);
int s[10][10]={};
const int n = argc-1;
for(int i = 1; i< argc; ++i)
a[i] = atoi(argv[i]);
copy(a.begin(), a.end(), ostream_iterator(cout, " "));
cout << endl << "----" << endl;
for(int i = 1; i<= n; ++i)
s[i][i] = a[i];
for ( int i = 1; i <= n; ++i )
{
for (int j = i+1; j <=n; ++j)
{
s[i][j] = s[i][j-1] + a[j];
printf("[%d][%d] = %d ", i, j, s[i][j]);
/* if s[i][j] is the required result print it,
* and the sub array is [i,j]
* */
}
printf("\n");
}
return 0;
}
No comments:
Post a Comment