Best Time to Buy and Sell Stock

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 sell one share of the stock), design an algorithm to find the maximum profit.

01 class Solution {
02 public:
03     int maxProfit(vector<int> &prices) {
04         // Start typing your C/C++ solution below
05         // DO NOT write int main() function
06         int n=prices.size();
07         if(n<=1)
08             return 0;
09         int result=0;
10         int min=prices[0];
11         for(int i=1;i<n;i++)
12         {
13             if(prices[i]<min)
14             {
15                 min=prices[i];
16                 continue;
17             }
18             int profit=prices[i]min;
19             if(profit>result)
20                 result=profit;
21         }
22         return result;
23     }
24 };
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s