码迷,mamicode.com
首页 > 其他好文 > 详细

Best Time to Buy and Sell Stock系列

时间:2016-03-24 13:01:55      阅读:113      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!