首页 > 其他 > 详细

Best Time to Buy and Sell Stock系列

时间:2016-03-24 12:58:41      阅读:218      评论:0      收藏:0      [点我收藏+]

I题

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.

Subscribe to see which companies asked this question

解答:采用动态规划解法,遍历数组更新当前最小值,并用当前值减去最小值与当前最大利润进行比较,更新最大利润。

public class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0) {
            return 0;
        }
        int min = Integer.MAX_VALUE;
        int profit = 0;
        for (int i : prices) {
            min = Math.min(min, i);
            profit = Math.max(i - min, profit);
        }
        return profit;
    }
}

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). 

Subscribe to see which companies asked this question

解答:采用贪心算法,记录相邻两天的差值,大于零则加到利润总量中。

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

 

Best Time to Buy and Sell Stock系列

原文:http://www.cnblogs.com/shinning/p/5314952.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!