leetcode5: 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.
#simple way.
class Solution {
public:
int maxProfit(vector<int> &prices) { // Start typing your C/C++ solution below // DO NOT write int main() function if(prices.size() <=1 ) return 0; int curMin = prices[0]; int maxProfit = 0; int profit = 0; for(int i=1; i!=prices.size(); ++i) { profit = prices[i] - curMin; if(maxProfit < profit) { maxProfit = profit; } if(prices[i] < curMin) curMin = prices[i]; } return maxProfit; } };
#divide and conquer in CRLS
class Solution { public: int minVal(vector<int> &prices, int low, int high){ int min = prices[low]; for( int i= low+1; i<=high; ++i) { if( prices[i] < min) { min = prices[i]; } } return min; } int maxVal(vector<int> &prices, int low, int high){ int max = prices[low]; for( int i= low+1; i<=high; ++i) { if( prices[i] > max) { max = prices[i]; } } return max; } int maxRec(vector<int> &prices, int low , int high){ if( low >=high ) return 0; int mid = (low + high) / 2; int left = maxRec( prices, low, mid); int right = maxRec( prices, mid+1, high); int left_min = minVal( prices, low, mid); int right_max = maxVal(prices, mid+1, high); return max( left, max( right, right_max - left_min) ); } int maxProfit(vector<int> &prices) { // Start typing your C/C++ solution below // DO NOT write int main() function int low = 0; int high = prices.size()-1; return maxRec( prices, low, high); } };
public class Solution { public int maxProfit(int[] prices) { // Start typing your Java solution below // DO NOT write main() function if(prices.length==0) return 0; int minPrice = prices[0]; int profit = 0; for(int i=1; i<prices.length; i++) { if( prices[i]-minPrice>profit) { profit = prices[i]-minPrice; } if(prices[i]<minPrice) minPrice = prices[i]; } return profit; } }