[leetcode] 121. Best Time to Buy and Sell Stock

来源:互联网 发布:brew install php扩展 编辑:程序博客网 时间:2024/05/29 15:09

题目:
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.

具体代码:

public class Solution {    public int maxProfit(int[] prices) {        if(prices.length<=1){            return 0;        }        int result = 0;        int min = prices[0];        for(int i = 1; i < prices.length; i++){            int temp = prices[i] - min;            if(result < temp){                result = temp;            }            if(min > prices[i]){                min = prices[i];            }        }        return result;    }}
0 0