A:
This answer uses the "simple" technique. It works well in practice, but can be improved. A second approach is discussed in the link. There, the algorithm is much simpler, and you can calculate the maximum profit explicitly.
Run through the array and add up the value of the items. Set P=0.
Return the highest number in the array.
Repeat: Add P to the current maximum profit, and remove the largest value from the array. If there are no more values, stop.
Repeat the second part of step 3.
This should run in O(n), as it has to iterate over the array only once.
A:
As simple as this:
public static void main(String] args) {
int[ numbers = { 1, 3, 2, 5, 8, 7 };
int result = 0;
for(int i = 0; i < numbers.length; i++) {
result += numbersi;
}
System.out.println(result);
}
The array is