I love the word "imputed."
That said, why is David called a man after God's own heart? I believe that is because in spite of all his failings David kept seeking the Lord with all his heart.
I do as well. When we are "in Christ" our sin debt is not imputed to us because if it were we would spend eternity separated from God paying that debt. But Christ's righteousness is imputed to us instead because ONLY his perfect righteousness is good enough to merit heaven.
It is this righteousness of Christ within us, the presence of the indwelling Holy Spirit, that compels us to live in a way that brings glory to God. That is why we ARE free from the law of sin and death and free to be ABLE to obey God out of a heart that has been intrinsically changed. We love him because he first love us.
The example of King David, who I'm sure would be the first to admit he failed often, is a man who, in spite of all his faults, STILL had faith and never let go of it. Rather than our salvation being a roller coaster ride of are we saved/aren't we saved based on how good we are, we have the assurance that we have been called by God into a relationship that began by grace and will culminate in that same grace with faith as the essential element. What He has begun in us HE will complete.