Skip to content

Commit 2631a95

Browse files
committed
Comment for explanation
1 parent f31febd commit 2631a95

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Cpp/maxValueProfit.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,41 @@
22
#include <algorithm>
33
#include <iostream>
44

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+
540
long maxValue(int n, std::vector<std::vector<int>>& rounds) {
641
std::vector<long> investments(n + 1, 0); // Initialize the investment array with n+1 elements, all set to 0
742

0 commit comments

Comments
 (0)