leetcode--Best Time to Buy and Sell Stock

来源:互联网 发布:翻译软件哪个好 编辑:程序博客网 时间:2024/05/21 08:36

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.

[java] view plain copy
  1. public class Solution {  
  2.     public int maxProfit(int[] prices) {  
  3.        int max = 0;  
  4.        if(prices.length==0return max;  
  5.        int min = prices[0];  
  6.        for(int i=1;i<prices.length;i++){  
  7.            if(prices[i]>min){  
  8.                if(prices[i]-min>max){  
  9.                    max = prices[i]-min;  
  10.                }  
  11.            }else{  
  12.                min = prices[i];  
  13.            }  
  14.        }  
  15.        return max;  
  16.     }  
  17. }  

原文链接http://blog.csdn.net/crazy__chen/article/details/46522367