Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

268
Views
Calculate all possible sums in an array from its sub arrays

I have an array of numbers, now I have to find sum of elements by generating all the possible subarrays of the given array and applying some conditions.

The condition is for each subarray get the minimum and also find the total of elements in it and multiply both (minimum * total). Finally, add all these multiplied values for all subarrays.

Here is the problem statement:

Find the sum of all possible sub-arrays using the below formula:

Sum(left, right) = (min of arr[i]) * (∑ arr[i]), where i ranges from left to right.

Example:

Array = [2,3,2,1]

The sub arrays are: [start_index, end_index]

 [0,0] subarray = [2], min is 2 and total of items = 2. min * total = 2*2=4
 [0,1] subarray = [2,3], min is 2 and total of items = 5. min * total = 2*5=10
 [0,2] subarray = [2,3,2], min is 2 and total of items = 7. min * total = 2*7=14
 [0,3] subarray = [2,3,2,1], min is 1 and total of items = 8. min * total = 1*8=8

 [1,1] subarray = [3], min is 3 and total of items = 3. min * total = 3*3 = 9
 [1,2] subarray = [3,2], min is 2 and total of items = 5. min * total = 2*5 = 10
 [1,3] subarray = [3,2,1], min is 1 and total of items = 6. min * total = 1*6 = 6

 [2,2] subarray = [2], min is 2 and total of items = 2. min * total = 2*2 = 4
 [2,3] subarray = [2,1], min is 1 and total of items = 3. min * total = 1*3 = 3

 [3,3] subarray = [1], min is 1 and total of items = 1. min * total = 1*1 = 1
 
 Total = 4 + 10 + 14 + 8 + 9 + 10+ 6 + 4 + 3 + 1 = 69
 

So the answer is 69 in this case.

Constraints:

Each array element is in range 1 to 10^9. Array size 1 to 10^5. Return response in modulo 10^9+7

This is the code I tried.

public static int process(List<Integer> list) {
    int n = list.size();
    int mod = 7 + 1000_000_000;
    long result = 0;
    for (int i = 0; i < n; i++) {
        long total = 0;
        int min = list.get(i);
        for (int j = i; j < n; j++) {
            int p = list.get(j);
            total = (total + p) % mod;
            min = Math.min(min, p);
            result = (result + (min * total) % mod) % mod;
        }
    }
    return (int) result;
}

I want to reduce the time complexity of this algorithm?

What can be a better approach to solve this task?

Update:

David Eisenstat has given a great answer, but Im finding it to difficult to understand and come with a Java program, can someone provide a java solution for the approach or provide a pseudo code so i can come up with a program.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Your current solution has time complexity O(n^2), assuming that list.get is O(1). There are exactly 1 + 2 + ... + n-1 + n operations which can be expressed as n * (n + 1)/2, hence O(n^2).

Interestingly, n * (n + 1)/2 is the number of sub arrays that you can get from an array of length n, as defined in your question and evident from your code.

This implies that you are doing one operation per sub array and this is the requird minimum operations for this task, since you need to look at least once at each sub array.

My conclusion is that it isn't possible to reduce the time complexity of this task, unless there is some mathematical formula that helps to do so.

This doesn't necessary mean that there aren't ways to optimize the code, but that would need testing and may be language specific. Regardless, it wouldn't change the time complexity in terms of n where n is the length of the input array.

Appreciate any input on my logic. I'm learning myself.

over 4 years ago · Santiago Trujillo Report

0

The answer provided by David Eisenstat is very efficient with complexity of O(n).

I would like to share another approach, that although it has time complexity of O(n^2), it may be more simple and may be easier for some (me included) to fully understand.

Algorithm

  1. initiate two dimensional array of size matrix[n][n], each cell will hold pair of Integers <sum, min>. we will denote for each Matrix[i, j] the first element of the pair as Matrix[i, j].sum and the second as Matrix[i, j].min
  2. Initiate the diagonal of the matrix as follows:
for i in [0, n-1]:
    Matrix[i][i] = <arr[i], arr[i]>
for i in [0, n-1]:
   for j in[i, n-1]:
        Matrix[i, j] = < 
            Matrix[i - 1, j].sum + arr[i, j], 
            Min(Matrix[i - 1, j].min, arr[i, j]) 
        >
  1. Calculate the result:
result = 0
for i in [0, n-1]:
   for j in[i, n-1]:
       result += Matrix[i, j].sum * Matrix[i, j].min

Time Complexity Analysis

  • Step 1: initiating two dimensional array ofsize [n,n] will take in theory O(n^2) as it may require to initiate all indices to 0, but if we skip the initialization of each cell and just allocate the memory this could take O(1)

  • Step 2 : Here we iterate from 0 to n-1 doing constant work each iteration and therefore the time complexity is O(n)

  • Step 3: Here we iterate over half of the matrix cells(all that are right of the diagonal), doing constant work each iteration, and therefore the time complexity is O((n - 1) + (n - 2) + .... + (1) + (0)) = O(n^2)

  • Step 4: Similar analysis to step 3, O(n^2)

In total we get O(n^2)

Explanation for solution

This is simple example of Dynamic programming approach.

Let's define sub[i, j] as the subarray between index i and j while 0 =< i, j <= n-1

Then:

  • Matrix[i, j].sum = sum x in sub[i, j]
  • Matrix[i, j].min = min x in sub[i, j]

Why?

for sub[i,i] it's obvious that:

  • sum x in sub[i, i] = arr[i]
  • min x in sub[i, i] = arr[i]

Just like we calculate in step 2.

Convince yourself that:

  • sum sub[i,j] = sum sub[i-1,j] + arr[i, j]
  • min sub[i,j] = Min(min sub[i-1,j], arr[i, j])

This explains step 3.

In Step 4 we just sums up everything to get the required result.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!