Minimum Cost to Connect Sticks - Critique
The solution to the problem 'Minimum Cost to Connect Sticks' explains that using sorting is an n-squared approach, and ends up using a Heap for an optimal complexity:
time complexity: o(N log(N))
space complexity: o(N)
Here N, is the length of the array given in the problem.
However, I do feel sorting gives the optimal solution, not using heap.
This is possible by not using extra space at all.
I have a better complexity of:
time complexity: O(N log(N))
Space complexity: o(1).
This is Assertion 1.
Down the line, I hope to add a more formal analysis as to prove why this approach is better than using a heap, or an update saying I was wrong to use sorting first.
For now, here are my thoughts on the matter.
Here is my algorithm:
- Sort the given array, in ascending order. The fastest algorithm we have is O(N log(N)).
- [comment] Now, any other operation needs to either match or be faster to preserve the truth of Assertion 1.
- The only speeds left are o(1), o(logN) and o(N).
- This algorithm uses o(N).
- Iterate through the array, using a sliding window of 2.
- Start the iteration at 2nd value.
- In c#, arrays start at 0, not 1.
- So the 2nd term is at the index of 1, not 2.
- Here's a joke:
- Professor: "Compile error? Just check for out of bounds, you must have done 1-based indexing - java uses 0 based indexing, so when your math is off, the system thinks you are referencing something that doesn't exist. Computers need to be told every damn thing, and humans count from 1."
- Student: 'I am using Lua, Professor.'
- Fun fact! - Lua's data structures indexing start at 1. Not 0. It's an outlier among programing languages.
- Keep track of some variables, per iteration:
- Keep track of i.
- Keep track of i -1.
- Keep track of array[i] .
- Keep track of array[i-1].
- currentCost = array[i] + array[i-1]
- mininumCost = minimumCost + currentCost
- Set array[i] to currentCost.
- [comment] Every iteration, currentCost will be calculated to be the sum of previous 2 elements. mininumCost keeps increasing per iteration. Finally, because of b.vii , the next iteration will reference currentCost as the base of b.1v
- [comment] The loop is to continue until the program flow reaches the length of the array, minus 1.
- [comment] In it's last iteration, currentCost will be added to minimumCost.
- Return minimumCost.
Member discussion