The trick here is to name the state correctly, then let the implementation follow. For 1281. Subtract the Product and Sum of Digits of an Integer, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: straightforward implementation.
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are subtractProductAndSum.
Guide
Why?
The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Read the setup variables first.
- Follow the main loop or recursive helper next.
- Watch where invalid states get skipped.
- Check which value survives to the return statement.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 4 ms, faster than 51.60% of C++ online submissions for Subtract the Product and Sum of Digits of an Integer.
02//Memory Usage: 8.2 MB, less than 100.00% of C++ online submissions for Subtract the Product and Sum of Digits of an Integer.
03
04class Solution {
05public:
06 int subtractProductAndSum(int n) {
07 int product = 1, sum = 0;
08
09 while(n > 0){
10 int d = n%10;
11 product *= d;
12 sum += d;
13 n /= 10;
14 }
15
16 return product - sum;
17 }
18};
Cost