Say you have an array for which the ith element are the price of a given the
If you are were only permitted to complete in most one transaction (ie, buy one and sell one share of the "stock", design an AL Gorithm to find the maximum profit.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
output:5
max. difference = 6-1 = 5 (Not 7-1 = 6, as selling price needs to be larger th An buying price)
Example 2:
Input: [7, 6, 4, 3, 1] output:0 in this case
, no transaction are done, i.e. Max Profit = 0.
A set of numbers is the stock price in chronological order, and how to operate it at once can get the maximum profit.
Dynamic planning Public
int Maxprofit (int[] prices) {
//[7, 1, 5, 3, 6, 4]
int local = 0;
int global = 0;
for (int i = 0; i < prices.length-1 i++) {Local
= Math.max (local+prices[i+1]-prices[i],0);//Current optimal solution
Global = Math.max (local, global);
return global;
}