Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

C++:
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=0;
11         int max=0;
12         bool flag=false;
13         for(int i=0;i<n;i++)
14         {
15             if(flag==false)
16             {
17                 if(i==n1)
18                     return result;
19                 if(prices[i]>prices[i+1])
20                     continue;
21                 min=prices[i];
22                 flag=true;
23 
24             }
25             if(flag=true)
26             {
27                 max=max>prices[i]?max:prices[i];
28                 if(i==n1)
29                 {
30                     return result+maxmin;
31                 }
32                 if(prices[i]>prices[i+1])
33                 {
34                     result+=maxmin;
35                     min=0;
36                     max=0;
37                     flag=false;
38                 }
39             }
40         }
41     }
42 };
Advertisements
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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s