Skip to content

Competitive coding 10 completed - #466

Open
sujaygijre wants to merge 2 commits into
super30admin:masterfrom
sujaygijre:master
Open

Competitive coding 10 completed#466
sujaygijre wants to merge 2 commits into
super30admin:masterfrom
sujaygijre:master

Conversation

@sujaygijre

Copy link
Copy Markdown

No description provided.

@super30admin

Copy link
Copy Markdown
Owner

Your solution for the stock problem uses a valley-peak approach which is valid and achieves O(n) time complexity and O(1) space complexity, which is optimal. This is much better than the recursive reference solution.

Strengths:

  • The algorithm efficiently captures every profitable transaction by identifying local minima and maxima.
  • The code is concise and uses constant space.

Areas for improvement:

  1. There is a syntax error in your code: a stray closing bracket ']' after the declaration of profit. This will cause a compilation error. You should remove it.
  2. The initialization of valley and peak to INT_MAX and INT_MIN is unnecessary because they are assigned inside the loop before being used. You can simply declare them without initialization or initialize to 0.
  3. The algorithm can be simplified. You can achieve the same result by simply iterating through the array and adding the positive differences between consecutive days. For example:
    int profit = 0;
    for (int i=1; i<prices.size(); i++) {
    if (prices[i] > prices[i-1])
    profit += prices[i] - prices[i-1];
    }
    This approach is simpler and avoids nested while loops.
  4. Consider edge cases: although your code handles arrays of length 1 correctly, the simplified version would be easier to understand.

Additionally, note that the problem allows buying and selling on the same day, which means we can capture every daily increase. The simplified code directly leverages this.

Unrelated note: you included a second file (peekingIterator.cpp) which is not part of the stock problem. Please make sure to only submit the solution for the problem you are solving.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants