LintCode_149_买卖股票的最佳时机

来源:互联网 发布:sql server数据库开发 编辑:程序博客网 时间:2024/05/17 03:02

假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。

样例

给出一个数组样例 [3,2,3,1,2], 返回 1 

两个循环 前后找差值最大的

public class Solution {    /**     * @param prices: Given an integer array     * @return: Maximum profit     */    public int maxProfit(int[] prices) {        // write your code here        int profit = 0;                for(int i = prices.length - 1 ; i > 0 ; i--){            for(int j = 0; j < i ; j++){                int temp = prices[i] - prices[j];                if(temp > profit){                    profit = temp;                }            }        }        return profit;    }}


0 0