-2

I have a array A and want a array B of same size of A where B[i] represent length of continous subarray start with A[i] in which all elements are less than or equal to A[i]

Example

A={1,3,4,2,4,5,1,6} 

Output

B={1,1,3,1,1,2,1,1} 

Explanation :

For A[2]=4 there is a subarray with element{4,2,4}, for A[5]=5 there is a subarray {5,1} for A[7]=6 there is subarray {6}

LHH
  • 3,233
  • 1
  • 20
  • 27
  • Can't find any question. – vdolez Aug 12 '15 at 12:01
  • It seems like if you copy-pasted you homework assignment and want an answer that you could copy-paste and submit as your homework. That kind of questions isn't much welcomed here. Try adding what have you tried and why it failed. Also, I have solved this problem as an subproblem in [this](http://stackoverflow.com/questions/31890785/counting-according-to-query/31928012#31928012) answer. – kajacx Aug 12 '15 at 19:15

2 Answers2

0
You can apply below algorithm to get the answer for your problem:-

Array B =[]; //initialize blank array
for (int i=0; i< A.length(); i++)
{
    j=i;
    length=1;
    while(i< A.length()-1)
    {
        j++;
        if(A[j]<=A[i])
            length++;
        else
            break;
    }
B[i]= length;
}

Print B // This will give you the similar array as of Array "A". 
QASource
  • 65
  • 1
0

Complexity: O(n)

#include <iostream>
#include <fstream>
using namespace std;

#define max 10000

int main(int argc, const char * argv[]) {

    ifstream input("/Users/appleuser/Documents/Developer/xcode projects/SubArrayCount/SubArrayCount/input.in");

    int n, arr[max], after[max]={0};
    input >> n;
    for (int i=0; i<n; i++)
        input >> arr[i];

    for (int i=n-1;i>=0;i--)
        for (int j=i+1;j<n&&arr[j]<=arr[i];j+=after[j]+1)
        {
            if (arr[j]==arr[i])
            {
                after[i]++;
                break;
            }
            after[i]+=after[j]+1;
        }


    for (int i=0; i<n; i++)
        cout << after [i] << " ";
    cout << endl;

    return 0;
}
hasan
  • 23,815
  • 10
  • 63
  • 101