The best time to buy and buy stocks
The best time to buy and buy stocks
Description: Suppose there is an array whose I-th element is the price of a given stock on the I-th day. If you are allowed to complete a transaction at most once (for example, a stock transaction), design an algorithm to find the maximum profit.
Example
An array example [3, 2, 3, 1, 2] is provided, and 1 is returned.
I just made this question in LintCode. At first, it was because of the for loop nesting problem and the running time timed out. Is the following a substitute?
class Solution {public: /** * @param prices: Given an integer array * @return: Maximum profit */ int maxProfit(vector<int> &prices) { // write your code here /*if(pirces.size()==0){ return 0;}*/ if(prices.size()==0) return 0; int max=0,sum=prices.size(); int i,j; for(i=0;i<sum-1;i++) { for(j=0;j<sum-1-i;j++) { if(prices[i]<prices[i+j+1]&&max<prices[i+j+1]-prices[i]) max=prices[i+j+1]-prices[i]; } } return max; }};
Below I discard a for Loop
class Solution {public: /** * @param prices: Given an integer array * @return: Maximum profit */ int maxProfit(vector<int> &prices) { // write your code here /*if(pirces.size()==0){ return 0;}*/ if(prices.size()==0) return 0; int min=prices[0],max=0,sum=prices.size(); for(int i=0;i<sum-1;i++) { if(prices[i+1]<min) { min=prices[i+1]; } else { if(max<prices[i+1]-min) max=prices[i+1]-min; } } return max; }};