This paper uses optimization theory to address a fundamental question of ethics: how to divide resources justly among individuals, groups, or organizations. It formulates utilitarian and Rawlsian criteria for distributive justice as optimization problems. The formulations recognize that some recipients are more productive than others, so that an inequitable distribution may create greater overall utility. Conditions are derived under which a distribution of resources is utility maximizing, and under which it achieves a lexicographic maximum, which we take as formulating the difference principle of John Rawls. It is found that utility maximization requires at least as much inequality as results from allotting resources in proportion to productivity, and typically a good deal more. Rawlsian justice requires a greater degree of equality than utilitarianism, particularly when the distribution of productivities across recipients has a short upper tail, although it is insensitive to the lower tail. It also requires greater equality when there are rapidly decreasing returns to investment in productivity, and ironically, when people have a stronger interest in getting rich.