Best Time to Buy and Stock, sellstock
This article is in the study of the summary, welcome to reprint but please note the Source: http://blog.csdn.net/pistolove/article/details/43024967
Say you have an array for which the ith element is the price of a given stock on day I.
If you were only permitted to complete at most one transaction (ie, buy one and every one share of the stock), design an algorithm to find the maximum profit.
Ideas:
(1) The question is to give an array. The value of element I in the array corresponds to the stock on the day I. Please only make one transaction, that is, buy and sell once, the maximum profit.
(2) This question examines the maximum difference. For this question, if the value of day I is greater than the value of day I + 1, you will not be able to buy it if it is monotonic decreasing. Only the value of day I is less than the value of day I + 1, purchase can be profitable only when it is monotonically increasing. Therefore, traverse the array to compare the difference between adjacent elements, and obtain the maximum profit.
(3) I hope this article will help you.
The algorithm code is implemented as follows:
/** * @authod liqq */public int maxProfit(int[] prices) {int len = prices.length;if (prices == null || len <= 1)return 0;int curr = prices[0];int profit = 0;for (int i = 0; i < len; i++) {int nex = prices[i];profit = nex - curr > profit ? nex - curr : profit;curr = curr < nex ? curr : nex;}return profit;}