Leetcode OJ平台上的BestTimetoBuyandSellStockII题目用Java实现

上一篇 / 下一篇  2014-06-03 10:02:43 / 个人分类:学习

原题目如下,意思就是说同一天只能进行买或卖操作,求利润最大值。


这个题目的关键是寻找增序序列,好比股票走势图,在最低点买入,在最高点卖出来获取最大利润。


在木易先森的提醒下,使用了一个投机取巧的方法,即价格数组p[i] > p[i-1]的,直接用p[i]-p[i-1],然后把这些差值累加起来即可。它和找出增序序列起止点,然后计算差值的结果是一样的。赞!

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


源代码如下:

public class Solution {
    public static int maxProfit(int[] prices) {
        int profit=0;
        for(int i = 1; i < prices.length; i++){
            if(prices[i] > prices[i-1])
                profit += (prices[i]-prices[i-1]) ;
        }
        return profit;
    }
   
    public static void main(String agrs[]){
        int[] prices = {10,5,4,12,8,15};
        int profit = maxProfit(prices);
        System.out.println(profit);
        }
}


TAG:

 

评分:0

我来说两句

我的栏目

日历

« 2024-04-22  
 123456
78910111213
14151617181920
21222324252627
282930    

数据统计

  • 访问量: 17695
  • 日志数: 12
  • 建立时间: 2014-05-21
  • 更新时间: 2014-06-03

RSS订阅

Open Toolbar