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

122. Best Time to Buy and Sell Stock II

时间:2017-02-19 10:16:27      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:计算   which   design   sel   let   prim   public   target   algorithm   

题目:

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

Hide Tags
 Array Greedy 

链接: http://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

2/18/2017, Java

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         if (prices.length <= 1) return 0;
 4 
 5         boolean hasStock = false;
 6         int sumProfit = 0;
 7         int min = 0;
 8         
 9         for(int i = 0; i < prices.length - 1; i++) {
10             if (hasStock) {
11                 if (prices[i] > prices[i + 1]) {
12                     sumProfit += prices[i] - min;
13                     hasStock = false;
14                 }
15             } else {
16                 if (prices[i] < prices[i + 1]) {
17                     min = prices[i];
18                     hasStock = true;
19                 }
20             }
21         }
22         if (hasStock) sumProfit += prices[prices.length - 1] - min;
23         return sumProfit;
24     }
25 }

别人的思路:

只要计算数组里的升序和就可以了!二刷再做。

122. Best Time to Buy and Sell Stock II

标签:计算   which   design   sel   let   prim   public   target   algorithm   

原文地址:http://www.cnblogs.com/panini/p/6414573.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!