Frequency of each element of an array considering all contiguos subarrays

前端 未结 4 2029
别跟我提以往
别跟我提以往 2020-12-17 04:14

Consider an array A = [5,1,7,2,3]

All contiguos subarrays = { [5], [1], [7], [2], [3], [5,1], [1,7], [7,2], [2,3], [5,1,7], [1,7,2], [7,2,3], [5,1,7,2], [1,7,2,3],

4条回答
  •  难免孤独
    2020-12-17 04:53

    I am having hard time trying to explain my solution in words. I will just add the code. It will explain itself:

    #include 
    #include 
    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], before[max]={0}, after[max]={0}, result[max];
        input >> n;
        for (int i=0; i> arr[i];
    
        for (int i=0;i=0&&arr[j]=0;i--)
            for (int j=i+1;j

    Explanation for (before[i]+1)*(after[i]+1):

    for each value we need the numbers lies before and less than the value and the numbers lies after and less than the value.

      | 0  1  2  3  4  5 .... count of numbers less than the value and appears before.
    ---------------------
    0 | 1  2  3  4  5  6
    1 | 2  4  6  8  10 12
    2 | 3  6  9  12 15 18
    3 | 4  8  12 16 20 24
    4 | 5  10 15 20 25 30
    5 | 6  12 18 24 30 36
    . | 
    . |
    . |
    count of numbers less than the value and appears after.
    

    Example: for a number that have 3 values less than it and appears before and have 4 values less than it and appears after. answer is V(3,4) = 20 = (3+1) * (4+1)

    please, let me know the results.

提交回复
热议问题