|
2 | 2 | #include <algorithm>
|
3 | 3 | #include <iostream>
|
4 | 4 |
|
| 5 | +// To solve "Prefix sum" can be used. |
| 6 | +// So the question is that there is investors these are making investment |
| 7 | +// in the predefined range in array. At the end, maximum profit is desired. |
| 8 | +/* |
| 9 | +
|
| 10 | + 1 2 10 => 1 and 2 are the coordinates of the indices. 10 is the profit |
| 11 | +
|
| 12 | + Total profit |
| 13 | + 0 0 0 0 0 |
| 14 | + 1 2 10 10 10 |
| 15 | + 2 4 5 10 15 5 5 |
| 16 | + 3 5 12 10 10 17 17 12 |
| 17 | +
|
| 18 | + At the end max profit is 17. |
| 19 | +
|
| 20 | + In brute force, there can be double for loop to check each input vector and add them to result vector. |
| 21 | + This will lead time complexit for O(n^2) |
| 22 | +
|
| 23 | + To fix this time complexity we can use "Prefix sum" |
| 24 | + Instead of adding each rounds lets add only investment value as a start and end. |
| 25 | + For the first round between 1 and 2 there is 10 profit. |
| 26 | + So, in the investment vector investment[start] += 10; and investment[end-1] -= 10; |
| 27 | + start = 1; end = 2; |
| 28 | + This is because instead of adding each profit in each step, we can track the positons |
| 29 | + and at the end we can add them together (prefix sum) to find the maximum profit/investment |
| 30 | +
|
| 31 | + In simple example lets assume between 2 and 6 we need to add 5 |
| 32 | + vector should be [0 5 5 5 5 5 0 0] |
| 33 | + instead of wrtting like this. lets use start and end points |
| 34 | + [0 5 0 0 0 0 0 -5] (vector size should be round+1). |
| 35 | + then lets use prefix sum to get same result |
| 36 | + vec[1] = 0; vec[2] = vec[1] + vec[2]; vec[3] = vec[0] + vec[1] + vec[2]; ..... |
| 37 | + Result = s[0 5 5 5 5 5 5 0]. |
| 38 | +*/ |
| 39 | + |
5 | 40 | long maxValue(int n, std::vector<std::vector<int>>& rounds) {
|
6 | 41 | std::vector<long> investments(n + 1, 0); // Initialize the investment array with n+1 elements, all set to 0
|
7 | 42 |
|
|
0 commit comments