Background
Hello everyone! I am trying to solve a problem from CSES which uses greedy algorithm. I wanted to prove the correctness of the solution formally, but I’ve found it quite challenging. I’d really appreciate any guidance or thoughts to help me think through the proof.
Here is the link to my original coding problem: https://cses.fi/problemset/task/1092/
Problem
Given the set $\{1,2,\ldots,n\}$ and a target sum $S$ (where $S\le \sum_{i=0}^n i$), find a subset of distinct elements that adds up to $S$, which contains the largest possible elements
Question
I designed a greedy algorithm that works like this:
Start from $n$. While the remaining sum is not 0, at each step, if the current number is less than or equal to the sum, include it in the subset and subtract it from the sum. Repeat until the remaining sum becomes zero.
I’ve tested this algorithm and it seems to work well, but I’m struggling to prove its correctness formally. Specifically:
- Why this greedy approach always leads to a valid subset (one in which the elements add up to $S$, using the largest possible elements)?
- How to write a clear proof (e.g., termination + correctness/invariant)?